在.CSS文件中创建一个变量,在.CSS文件[duplicate]中使用

时间:2022-06-19 00:09:54

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;
}

13 个解决方案

#1


89  

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.

通过这种方式,您可以避免重复概念上相同的样式,同时也可以清楚地说明它们影响文档的哪些部分。

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的存在:两个属性共享相同的值并不一定意味着他们表示相同的概念。夜晚的天空可能是红色的,西红柿也可能是红色的——但是天空和西红柿不一样的原因是红色的,它们的颜色会随着时间的变化而变化。同样地,仅仅因为样式表中有两个元素被赋予相同的颜色或大小或位置,并不意味着它们总是共享这些值。使用分组(如此处所述)或使用SASS或更少的变量处理器以避免价值重复的天真设计人员可能会对样式进行不可思议的错误更改;在减少重复时,总是关注样式的上下文含义,忽略它们当前的值。

#2


15  

You can achieve it and much more by using Less CSS.

您可以通过使用更少的CSS来实现它,并且可以做得更多。

#3


6  

No, but Sass does 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,但是也有一个通用的编译器,可以根据需要为您进行编译。

#4


5  

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.

你并不是第一个感到疑惑的人,答案是否定的。Elliotte发表了一篇精彩的演说:http://cafe.elharo.com/web/css-repeats-itself/。您可以在运行时使用JSP或其等效的JSP来生成CSS。

#5


3  

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发送到客户机之前对其进行预处理。

#6


3  

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).

不过,似乎至少有一些来自浏览器世界的人正在研究它。因此,如果它在将来的某个时候真的成为标准,那么我们将不得不等到它在所有浏览器中实现(在那之前它将无法使用)。

#7


2  

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的建议进行预处理。您可能想要使用一个allready存在的:m4

http://www.gnu.org/software/m4/m4.html

http://www.gnu.org/software/m4/m4.html

#8


2  

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>

#9


2  

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 argument that any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation.

我已经编写了一个宏(在Visual Studio中),它不仅允许我为命名颜色编写CSS代码,还允许我轻松地计算这些颜色的阴影或混合。它还处理字体。它启动save并输出一个单独的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:

这种方法的目标如下:

  1. 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

    允许基本颜色、字体等在一个中心位置被定义,这样就可以轻松地调整整个pallete或排版处理,而不必使用search/replace。

  2. Avoid having to map the .CSS extension in IIS

    避免在IIS中映射.CSS扩展。

  3. Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode

    生成可以使用的普通文本CSS文件,例如,通过VisualStudio的设计模式

  4. Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested

    在创作时生成这些文件,而不是每次请求CSS文件时重新计算它们。

  5. Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow

    立即和透明地生成这些文件,而不需要添加额外的步骤来进行调整-保存测试工作流程。

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文件必须被称为常量。并且必须与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文件时,ProcessCSS方法就会被environmentmentevents触发。CSS文件被展开,文件的扩展的静态版本被保存在/ CSS /静态/文件夹中。(所有HTML页面都应该引用/css/静态/css文件的版本)。

The Constants.xml file might look something like this:

的常数。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 */

#10


1  

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变量建议,但是目前,您需要使用预处理器。

#11


1  

You can use mutliple classes in the HTML element's class attribute, each providing part of the styling. So you could define your CSS as:

您可以在HTML元素的class属性中使用mutliple类,每个类都提供了样式的一部分。你可以定义CSS为:

.ourColor { color: blue; }
.ourBorder { border: 1px solid blue; }
.bigText { font-size: 1.5em; }

and then combine the classes as required:

然后按要求合并类:

<h1 class="ourColor">Blue Header</h1>
<div class="ourColor bigText">Some big blue text.</div>
<div class="ourColor ourBorder">Some blue text with blue border.</div>

That allows you to reuse the ourColor class without having to define the colour mulitple times in your CSS. If you change the theme, simply change the rule for ourColour.

这允许您重用ourColor类,而无需在CSS中定义颜色的多倍时间。如果你改变主题,只需改变颜色规则。

#12


1  

This may sound like insanity, but if you are using NAnt (or Ant or some other automated build system), you can use NAnt properties as CSS variables in a hacky way. Start with a CSS template file (maybe styles.css.template or something) containing something like this:

这听起来可能有点疯狂,但如果您正在使用NAnt(或Ant或其他自动构建系统),那么您可以以一种不常用的方式将NAnt属性用作CSS变量。从CSS模板文件开始(可能是styles.css)。模板或其他)包含如下内容:

a {
    color: ${colors.blue};
}

    a:hover {
        color: ${colors.blue.light};
    }

p {
    padding: ${padding.normal};
}

And then add a step to your build that assigns all the property values (I use external buildfiles and <include> them) and uses the <expandproperties> filter to generate the actual CSS:

然后在构建中添加一个步骤来分配所有的属性值(我使用外部构建文件和 <包括> ),并使用 过滤器生成实际的CSS:

<property name="colors.blue" value="#0066FF" />
<property name="colors.blue.light" value="#0099FF" />
<property name="padding.normal" value="0.5em" />

<copy file="styles.css.template" tofile="styles.css" overwrite="true">
    <filterchain>
        <expandproperties/>
    </filterchain>
</copy>

The downside, of course, is that you have to run the css generation target before you can check what it looks like in the browser. And it probably would restrict you to generating all your css by hand.

当然,它的缺点是,您必须运行css生成目标,才能检查它在浏览器中的外观。它可能会限制你手工生成css。

However, you can write NAnt functions to do all sorts of cool things beyond just property expansion (like generating gradient image files dynamically), so for me it's been worth the headaches.

但是,您可以编写NAnt函数来完成除了属性扩展之外的各种酷的事情(比如动态生成梯度图像文件),所以对我来说,这是值得头痛的事情。

#13


0  

CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.

CSS还没有使用变量,这是可以理解的,因为它是一种声明性语言。

Here are two major approaches to achieve more dynamic style handling:

以下是实现更动态样式处理的两种主要方法:

  • Server-side variables in inline css
    Example (using PHP):

    <style> .myclass{color:<?php echo $color; ?>;} </style>

    <时尚> .myclass {颜色:< ?php echo $颜色;>;} < /风格>

 

 

  • DOM manipulation with javascript to change css client-side
    Examples (using jQuery library):

    使用javascript进行DOM操作以更改css客户端示例(使用jQuery库):

    $('.myclass').css('color', 'blue');

    $(' .myclass ')。css(“颜色”、“蓝”);

    OR

    //The jsvarColor could be set with the original page response javascript
    // in the DOM or retrieved on demand (AJAX) based on user action. $('.myclass').css('color', jsvarColor);

    //可以使用DOM中的原始页面响应javascript /来设置jsvarColor,或者根据用户操作按需检索(AJAX)。$(' .myclass ')。css(“颜色”,jsvarColor);

#1


89  

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.

通过这种方式,您可以避免重复概念上相同的样式,同时也可以清楚地说明它们影响文档的哪些部分。

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的存在:两个属性共享相同的值并不一定意味着他们表示相同的概念。夜晚的天空可能是红色的,西红柿也可能是红色的——但是天空和西红柿不一样的原因是红色的,它们的颜色会随着时间的变化而变化。同样地,仅仅因为样式表中有两个元素被赋予相同的颜色或大小或位置,并不意味着它们总是共享这些值。使用分组(如此处所述)或使用SASS或更少的变量处理器以避免价值重复的天真设计人员可能会对样式进行不可思议的错误更改;在减少重复时,总是关注样式的上下文含义,忽略它们当前的值。

#2


15  

You can achieve it and much more by using Less CSS.

您可以通过使用更少的CSS来实现它,并且可以做得更多。

#3


6  

No, but Sass does 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,但是也有一个通用的编译器,可以根据需要为您进行编译。

#4


5  

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.

你并不是第一个感到疑惑的人,答案是否定的。Elliotte发表了一篇精彩的演说:http://cafe.elharo.com/web/css-repeats-itself/。您可以在运行时使用JSP或其等效的JSP来生成CSS。

#5


3  

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发送到客户机之前对其进行预处理。

#6


3  

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).

不过,似乎至少有一些来自浏览器世界的人正在研究它。因此,如果它在将来的某个时候真的成为标准,那么我们将不得不等到它在所有浏览器中实现(在那之前它将无法使用)。

#7


2  

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的建议进行预处理。您可能想要使用一个allready存在的:m4

http://www.gnu.org/software/m4/m4.html

http://www.gnu.org/software/m4/m4.html

#8


2  

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>

#9


2  

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 argument that any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation.

我已经编写了一个宏(在Visual Studio中),它不仅允许我为命名颜色编写CSS代码,还允许我轻松地计算这些颜色的阴影或混合。它还处理字体。它启动save并输出一个单独的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:

这种方法的目标如下:

  1. 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

    允许基本颜色、字体等在一个中心位置被定义,这样就可以轻松地调整整个pallete或排版处理,而不必使用search/replace。

  2. Avoid having to map the .CSS extension in IIS

    避免在IIS中映射.CSS扩展。

  3. Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode

    生成可以使用的普通文本CSS文件,例如,通过VisualStudio的设计模式

  4. Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested

    在创作时生成这些文件,而不是每次请求CSS文件时重新计算它们。

  5. Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow

    立即和透明地生成这些文件,而不需要添加额外的步骤来进行调整-保存测试工作流程。

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文件必须被称为常量。并且必须与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文件时,ProcessCSS方法就会被environmentmentevents触发。CSS文件被展开,文件的扩展的静态版本被保存在/ CSS /静态/文件夹中。(所有HTML页面都应该引用/css/静态/css文件的版本)。

The Constants.xml file might look something like this:

的常数。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 */

#10


1  

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变量建议,但是目前,您需要使用预处理器。

#11


1  

You can use mutliple classes in the HTML element's class attribute, each providing part of the styling. So you could define your CSS as:

您可以在HTML元素的class属性中使用mutliple类,每个类都提供了样式的一部分。你可以定义CSS为:

.ourColor { color: blue; }
.ourBorder { border: 1px solid blue; }
.bigText { font-size: 1.5em; }

and then combine the classes as required:

然后按要求合并类:

<h1 class="ourColor">Blue Header</h1>
<div class="ourColor bigText">Some big blue text.</div>
<div class="ourColor ourBorder">Some blue text with blue border.</div>

That allows you to reuse the ourColor class without having to define the colour mulitple times in your CSS. If you change the theme, simply change the rule for ourColour.

这允许您重用ourColor类,而无需在CSS中定义颜色的多倍时间。如果你改变主题,只需改变颜色规则。

#12


1  

This may sound like insanity, but if you are using NAnt (or Ant or some other automated build system), you can use NAnt properties as CSS variables in a hacky way. Start with a CSS template file (maybe styles.css.template or something) containing something like this:

这听起来可能有点疯狂,但如果您正在使用NAnt(或Ant或其他自动构建系统),那么您可以以一种不常用的方式将NAnt属性用作CSS变量。从CSS模板文件开始(可能是styles.css)。模板或其他)包含如下内容:

a {
    color: ${colors.blue};
}

    a:hover {
        color: ${colors.blue.light};
    }

p {
    padding: ${padding.normal};
}

And then add a step to your build that assigns all the property values (I use external buildfiles and <include> them) and uses the <expandproperties> filter to generate the actual CSS:

然后在构建中添加一个步骤来分配所有的属性值(我使用外部构建文件和 <包括> ),并使用 过滤器生成实际的CSS:

<property name="colors.blue" value="#0066FF" />
<property name="colors.blue.light" value="#0099FF" />
<property name="padding.normal" value="0.5em" />

<copy file="styles.css.template" tofile="styles.css" overwrite="true">
    <filterchain>
        <expandproperties/>
    </filterchain>
</copy>

The downside, of course, is that you have to run the css generation target before you can check what it looks like in the browser. And it probably would restrict you to generating all your css by hand.

当然,它的缺点是,您必须运行css生成目标,才能检查它在浏览器中的外观。它可能会限制你手工生成css。

However, you can write NAnt functions to do all sorts of cool things beyond just property expansion (like generating gradient image files dynamically), so for me it's been worth the headaches.

但是,您可以编写NAnt函数来完成除了属性扩展之外的各种酷的事情(比如动态生成梯度图像文件),所以对我来说,这是值得头痛的事情。

#13


0  

CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.

CSS还没有使用变量,这是可以理解的,因为它是一种声明性语言。

Here are two major approaches to achieve more dynamic style handling:

以下是实现更动态样式处理的两种主要方法:

  • Server-side variables in inline css
    Example (using PHP):

    <style> .myclass{color:<?php echo $color; ?>;} </style>

    <时尚> .myclass {颜色:< ?php echo $颜色;>;} < /风格>

 

 

  • DOM manipulation with javascript to change css client-side
    Examples (using jQuery library):

    使用javascript进行DOM操作以更改css客户端示例(使用jQuery库):

    $('.myclass').css('color', 'blue');

    $(' .myclass ')。css(“颜色”、“蓝”);

    OR

    //The jsvarColor could be set with the original page response javascript
    // in the DOM or retrieved on demand (AJAX) based on user action. $('.myclass').css('color', jsvarColor);

    //可以使用DOM中的原始页面响应javascript /来设置jsvarColor,或者根据用户操作按需检索(AJAX)。$(' .myclass ')。css(“颜色”,jsvarColor);