Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference one CSS rule within another?

Tags:

css

For example if I have the following HTML:

<div class="someDiv"></div> 

and this CSS:

.opacity {     filter:alpha(opacity=60);     -moz-opacity:0.6;     -khtml-opacity: 0.6;     opacity: 0.6;  } .radius {     border-top-left-radius: 15px;     border-top-right-radius: 5px;     -moz-border-radius-topleft: 10px;     -moz-border-radius-topright: 10px;     }  .someDiv {     background: #000; height: 50px; width: 200px;  /*** How can I reference the opacity and radius classes here      so this div has those generic rules applied to it as well ***/  } 

Like how in scripting languages you have generic functions that are used often written at the top of the script and every time you need to use that function you simply call the function instead of repeating all the code every time.

like image 879
Jake Avatar asked Oct 30 '10 19:10

Jake


People also ask

Can one CSS class refer to another?

You can just add a comma-separated list of classes in . radius , like . radius, . another, .

Can you assign multiple CSS rules to an element?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

How do I link CSS to other CSS?

The @import rule allows you to import a style sheet into another style sheet. The @import rule must be at the top of the document (but after any @charset declaration). The @import rule also supports media queries, so you can allow the import to be media-dependent.

How do you write nested CSS?

Direct Nesting. A style rule can be directly nested within another style rule if its selector is nest-prefixed. To be nest-prefixed , a nesting selector must be the first simple selector in the first compound selector of the selector.


1 Answers

No, you cannot reference one rule-set from another.

You can, however, reuse selectors on multiple rule-sets within a stylesheet and use multiple selectors on a single rule-set (by separating them with a comma).

.opacity, .someDiv {     filter:alpha(opacity=60);     -moz-opacity:0.6;     -khtml-opacity: 0.6;     opacity: 0.6;  } .radius, .someDiv {     border-top-left-radius: 15px;     border-top-right-radius: 5px;     -moz-border-radius-topleft: 10px;     -moz-border-radius-topright: 10px;     } 

You can also apply multiple classes to a single HTML element (the class attribute takes a space separated list).

<div class="opacity radius"> 

Either of those approaches should solve your problem.

It would probably help if you used class names that described why an element should be styled instead of how it should be styled. Leave the how in the stylesheet.

like image 80
Quentin Avatar answered Oct 03 '22 03:10

Quentin