开发者

Chaining CSS rules

开发者 https://www.devze.com 2023-01-06 22:28 出处:网络
I have defined some background colors that I\'ll be using on my site.So I can easily set the background color of different elements like:

I have defined some background colors that I'll be using on my site. So I can easily set the background color of different elements like:

.backgrou开发者_Go百科nd_highlite{
    background-color: rgb(231, 222, 207); /*Cream in my Coffee*/
}
.background_shadow{
    background-color: rgb(201, 179, 156);  /*Moose Mousse*/
}

Now, if I want all textarea elements on my page to have Moose Mousse color as their background I want to write another CSS rule that references back to .background_shadow, so I only have to change the rgb values in one place.

Something like:

textarea{
    height:50px;
    background-color: background_highlite  /* want to feed forward to keep the rgb in one place */
}

Is this possible with CSS?


People have been frustrated by CSS's simplistic structure, and have created pre-processors to write CSS more conveniently. Look at Less, for example, or CleverCSS.


You can assign all the elements the same class, and then set the background color in the class's CSS:

<textarea class="background_shadow">blah</textarea>

Keep in mind that you can assign a number of classes to any element, so you can use one class just to control the background color, and then use other classes for your other needs:

<textarea class="background_shadow another_class something_else">...</textarea>


Not really. http://dorward.me.uk/www/css/inheritance/ lists your main options.


Sorry, no. CSS does not support variables, or chaining.

however, there is a javascript library that allows that. http://lesscss.org/


The best you can do would be

.hilight textbox {
  background: black;
}
textbox {
  color: pink;
}
.background_shadow {
 background: grey;
}

Or, of course, you could add the .hilite class to your div.


You have two options to work with:

  1. Native CSS, which is possible, but not good to maintain.
  2. Preprocessor, like xCSS, which can create more cleaner code and provide variables.

For simple projects I assume, native CSS will be good. But in more complicated it`s best to use some sort of processors, like pals talked earlier.

In this method you can always use some human readable rule like: .blabla {min-height: 20px}, which pre-processor by your own logic transform to CSS, that all of our target browsers can understand, like .blabla {min-height: 20px; height: auto !important; height: 20px;} etc.

Also what I realy like in preprocessors is that you can right code, as here:

  • .specialClass extends .basicClass {} // see more at extends
  • .selector { a { display: block; } strong { color: blue; } } // see more at children
  • or what you needed is vars { $path = ../img/tmpl1/png; $color1 = #FF00FF; $border = border-top: 1px solid $color1; } // see more at vars
0

精彩评论

暂无评论...
验证码 换一张
取 消