且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 .CSS 文件中创建一个变量以在该 .CSS 文件中使用

更新时间:2022-12-27 21:27:46

没有要求选择器的所有样式都驻留在一个规则中,并且一个规则可以应用于多个选择器......所以翻转它周围:

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.