Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a CSS class inside another class?

Tags:

Is it possible to have one CSS class reference another? Instead of rewriting all the css code again?

For example, I have this:

.btn{
    /* Whatever btn related styles I have */
}

.btn:hover{
    box-shadow:0 0 4px black;
}

.btn:active{
    /* This is where I want to reference the '.red' class */
}

.red{
    /* There is a LOT of CSS code here for cross browser gradients */
}

The thing is, I'm already using the .red class as is in certain places, and I'd also like to apply the same gradient style to the 'active' state of all elements with the .btn class...

If you can help solve (it need not be the way I've requested it) this, I'd greatly appreciate it...

like image 628
Abhishek Avatar asked Jun 13 '11 06:06

Abhishek


People also ask

How do you call a class from another class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class.

Can you put a class within a class in CSS?

Nested rules are defined as a set of CSS properties that allow the properties of one class to be used for another class and contain the class name as its property. In LESS, you can use class or ID selectors to declare mixin in the same way as CSS styles.

How do I select a nested class in CSS?

To be nest-prefixed , a nesting selector must be the first simple selector in the first compound selector of the selector. If the selector is a list of selectors, every complex selector in the list must be nest-prefixed for the selector as a whole to be nest-prefixed.

Can CSS be nested?

CSS nesting provides the ability to nest one style rule inside another, with the selector of the child rule relative to the selector of the parent rule. Similar behavior previously required a CSS pre-processor.


1 Answers

You can't actually do a reference (one of CSS's major failings), but you can do this:

.btn:active, .red {
    /* Block A: Most (or all) of what used to just be in .red below */
}

.btn:active {
    /* Block B: Stuff *just* for .btn:active, if any */
}

.red {
    /* Block C: Stuff *just* for .red, if any */
}

The comma means that the definitions in the body of Block A apply separately to each of those selectors, and so they apply to any ".btn" elements that are ":active", and separately apply to any ".red" elements.

Block B and Block C are optional. They're for any definitions you only want to apply to the given selector. You usually list these after Block A because rules of equal specificity are applied top-to-bottom, so you can override anything from Block A that you want to in Block B or Block C, and those blocks will "win".

like image 74
T.J. Crowder Avatar answered Sep 17 '22 21:09

T.J. Crowder