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

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

问题描述

可能的重复:
避免 CSS 中的重复常量

我们在 CSS 表中重复使用了一些主题颜色".

We have some "theme colors" that are reused in our CSS sheet.

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

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天全站免登陆