在 .CSS 文件中创建一个变量以在该 .CSS 文件中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a variable in .CSS file for use within that .CSS file
提问by Clay Nichols
Possible Duplicate:
Avoiding repeated constants in CSS
可能的重复:
避免 CSS 中的重复常量
We have some "theme colors" that are reused in our CSS sheet.
我们有一些在我们的 CSS 表中重复使用的“主题颜色”。
Is there a way to set a variable and then reuse it?
有没有办法设置一个变量然后重用它?
E.g.
例如
.css
OurColor: Blue
H1 {
color:OurColor;
}
回答by Shog9
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 conceptuallythe same, while also making it clear which parts of the document they affect.
这样,您可以避免重复概念上相同的样式,同时也明确它们影响文档的哪些部分。
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 willvary 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 alwaysshare these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid valuerepetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaningof styles when looking to reduce repetition, ignoring their current values.
请注意最后一句话中对“概念上”的强调......这只是在评论中出现,所以我将对其进行扩展,因为多年来我已经看到人们一遍又一遍地犯同样的错误 -甚至早于 CSS 的存在:共享相同值的两个属性并不一定意味着它们代表相同的概念。晚上的天空可能会呈现红色,西红柿也是如此——但天空和西红柿不是出于同样的原因而变红,它们的颜色会随着时间的推移而独立变化。出于同样的原因,仅仅因为您的样式表中有两个元素被赋予相同的颜色、大小或位置并不意味着它们总是分享这些价值观。一个使用分组(如此处所述)或变量处理器(如 SASS 或 LESS)来避免值重复风险的天真设计师,使未来对样式的更改非常容易出错;在寻求减少重复时,始终关注样式的上下文含义,而忽略它们的当前值。
回答by Tim Sullivan
No, but Sassdoes this. It's a CSS preprocessor, allowing you to use a lot of shortcuts to reduce the amount of CSS you need to write.
不,但Sass 会这样做。它是一个 CSS 预处理器,允许您使用很多快捷方式来减少需要编写的 CSS 量。
For example:
例如:
$blue: #3bbfce;
$margin: 16px;
.content-navigation {
border-color: $blue;
color:
darken($blue, 9%);
}
.border {
padding: $margin / 2;
margin: $margin / 2;
border-color: $blue;
}
Beyond variables, it provides the ability to nest selectors, keeping things logically grouped:
除了变量之外,它还提供嵌套选择器的能力,使事物按逻辑分组:
table.hl {
margin: 2em 0;
td.ln {
text-align: right;
}
}
li {
font: {
family: serif;
weight: bold;
size: 1.2em;
}
}
There's more: mixins that act kind of like functions, and the ability to inherit one selector from another. It's very clever and very useful.
还有更多:mixin 的行为有点像函数,以及从另一个选择器继承一个选择器的能力。它非常聪明,非常有用。
If you're coding in Ruby on Rails, it'll even automatically compile it to CSS for you, but there's also a general purpose compiler that can do it for you on-demand.
如果您使用 Ruby on Rails 进行编码,它甚至会自动将其编译为 CSS,但也有一个通用编译器可以按需为您执行此操作。
回答by sblundy
You're not the first to wonder and the answer is no. Elliotte has a nice rant on it: http://cafe.elharo.com/web/css-repeats-itself/. You could use JSP, or its equivalent, to generate the CSS at runtime.
你不是第一个想知道的人,答案是否定的。艾略特对此有一个很好的咆哮:http: //cafe.elharo.com/web/css-repeat-itself/。您可以使用 JSP 或其等效项在运行时生成 CSS。
回答by Konrad Rudolph
CSS doesn't offer any such thing. The only solution is to write a preprocessing script that is either run manually to produce static CSS output based on some dynamic pseudo-CSS, or that is hooked up to the web server and preprocesses the CSS prior to sending it to the client.
CSS 不提供任何这样的东西。唯一的解决方案是编写一个预处理脚本,该脚本要么手动运行以基于某些动态伪 CSS 生成静态 CSS 输出,要么连接到 Web 服务器并在将 CSS 发送到客户端之前对其进行预处理。
回答by Farinha
That's not supported at the moment unless you use some script to produce the CSS based on some variables defined by you.
除非您使用某些脚本根据您定义的某些变量生成 CSS,否则目前不支持该方法。
It seems, though, that at least some people from the browser world are working on it. So, if it really becomes a standard sometime in the future, then we'll have to wait until it is implemented in all the browsers (it will be unusable until then).
不过,似乎至少有一些来自浏览器世界的人正在研究它。所以,如果它真的在未来某个时候成为一个标准,那么我们将不得不等待它在所有浏览器中实现(直到那时它将无法使用)。
回答by Daren Thomas
Since CSS does not have that (yet, I believe the next version will), follow Konrad Rudolphs advice for preprocesing. You probably want to use one that allready exists: m4
由于 CSS 没有那个(但是,我相信下一个版本会有),请遵循 Konrad Rudolphs 的预处理建议。你可能想使用一个已经存在的:m4
回答by Herb Caudill
I've written a macro (in Visual Studio) that allows me to not only code CSS for named colors but to easily calculate shades or blends of those colors. It also handles fonts. It fires on save and outputs a separate version of the CSS file. This is in line with Bert Bos's argumentthat any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation.
我编写了一个宏(在 Visual Studio 中),它不仅可以为命名颜色编写 CSS 代码,还可以轻松计算这些颜色的阴影或混合。它还处理字体。它在保存时触发并输出 CSS 文件的单独版本。这与Bert Bos 的论点一致,即 CSS 中的任何符号处理都发生在创作时,而不是在解释时。
The full setup along with all the code would be a bit too complicated to post here, but might be appropriate for a blog post down the road. Here's the comment section from the macro which should be enough to get started.
完整的设置和所有代码在这里发布会有点太复杂,但可能适合以后的博客文章。这是宏的注释部分,应该足以开始使用。
The goals of this approach are as follows:
这种方法的目标如下:
Allow base colors, fonts, etc. to be defined in a central location, so that an entire pallete or typographical treatment can be easily tweaked without having to use search/replace
Avoid having to map the .CSS extension in IIS
Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode
Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested
Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow
允许在中心位置定义基色、字体等,以便可以轻松调整整个调色板或印刷处理,而无需使用搜索/替换
避免在 IIS 中映射 .CSS 扩展名
生成可以使用的各种文本 CSS 文件,例如,VisualStudio 的设计模式
在创作时生成一次这些文件,而不是每次请求 CSS 文件时重新计算它们
立即透明地生成这些文件,无需在调整-保存-测试工作流程中添加额外的步骤
With this approach, colors, shades of colors, and font families are all represented with shorthand tokens that refer to a list of values in an XML file.
使用这种方法,颜色、颜色深浅和字体系列都用速记标记表示,这些标记引用 XML 文件中的值列表。
The XML file containing the color and font definitions must be called Constants.xml and must reside in the same folder as the CSS files.
包含颜色和字体定义的 XML 文件必须称为 Constants.xml,并且必须与 CSS 文件位于同一文件夹中。
The ProcessCSS method is fired by EnvironmentEvents whenever VisualStudio saves a CSS file. The CSS file is expanded, and the expanded, static version of the file is saved in the /css/static/ folder. (All HTML pages should reference the /css/static/ versions of the CSS files).
每当 VisualStudio 保存 CSS 文件时,都会由 EnvironmentEvents 触发 ProcessCSS 方法。CSS 文件被展开,并且文件的展开的静态版本保存在 /css/static/ 文件夹中。(所有 HTML 页面都应该引用 CSS 文件的 /css/static/ 版本)。
The Constants.xml file might look something like this:
Constants.xml 文件可能如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<cssconstants>
<colors>
<color name="Red" value="BE1E2D" />
<color name="Orange" value="E36F1E" />
...
</colors>
<fonts>
<font name="Text" value="'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif" />
<font name="Serif" value="Georgia,'Times New Roman',Times,serif" />
...
</fonts>
</cssconstants>
In the CSS file, you can then have definitions like:
在 CSS 文件中,您可以定义如下:
font-family:[[f:Text]];
background:[[c:Background]];
border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */
回答by Herb Caudill
You're making it too complicated. This is the reason the cascade exists. Simply provide your element selectors and class your color:
你把它弄得太复杂了。这就是级联存在的原因。只需提供您的元素选择器并对您的颜色进行分类:
h1 {
color: #000;
}
.a-theme-color {
color: #333;
}
Then apply it to the elements in the HTML, overriding when you need to use your theme colors.
然后将其应用到 HTML 中的元素,在您需要使用主题颜色时覆盖。
<h1>This is my heading.</h1>
<h1 class="a-theme-color">This is my theme heading.</h1>
回答by S?ren Kuklau
See also Avoiding repeated constants in CSS. As Farinha said, a CSS Variables proposal has been made, but for the time being, you want to use a preprocessor.
另请参阅避免 CSS 中的重复常量。正如 Farinha 所说,已经提出了 CSS Variables 提案,但目前,您希望使用预处理器。