在.CSS文件中创建一个变量,以便在.CSS文件中使用 [英] Create a variable in .CSS file for use within that .CSS file

查看:167
本文介绍了在.CSS文件中创建一个变量,以便在.CSS文件中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

避免在CSS中重复常数

颜色。

有没有办法设置一个变量,然后重用它?

Is there a way to set a variable and then reuse it?

例如

.css
OurColor: Blue

H1 { 
 color:OurColor;
}


推荐答案

对于选择器位于单个规则中,并且单个规则可以应用于多个选择器...因此翻转

There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around:

/* Theme color: text */
H1, P, TABLE, UL
{ color: blue; }

/* Theme color: emphasis */
B, I, STRONG, EM
{ color: #00006F; }

/* ... */

/* Theme font: header */
H1, H2, H3, H4, H5, H6
{ font-family: Comic Sans MS; }

/* ... */

/* H1-specific styles */
H1
{ 
   font-size: 2em; 
   margin-bottom: 1em;
}

这样,您就可以避免重复 >同样,同时也清楚它们影响的文档的哪些部分。

This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect.

注意在最后一句中概念上的重点...这只是在评论中提出的,所以我要展开一点,因为我已经看到人们一再重复这个错误多年 - 甚至预测CSS的存在:共享相同的值的两个属性不一定意味着它们代表相同的概念 >。天空在晚上可能会出现红色,而西红柿也会出现红色 - 但是天空和番茄因为同样的原因而不是红色,它们的颜色会随着时间的推移而发生变化。 出于同样的原因,只是因为您的样式表中有两个元素具有相同的颜色,大小或位置,并不意味着它们总是 共享这些值。使用分组(如本文所述)或可变处理器(例如SASS或LESS)以避免重复的值的天真设计者会使未来对样式的改变变得难以置信的容易出错;在查找减少重复时,始终专注于样式的上下文含义,忽略它们的当前值

Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values.

这篇关于在.CSS文件中创建一个变量,以便在.CSS文件中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆