CSS Class Inheritance in CSS
CSS Inheritance in the Markup
Suppose we have several different buttons that share the same base set of properties, we might do something like this with our CSS:
.button {
display: block;
border-radius: 5px;
background-color: gray;
color: white;
}
.button-primary {
background-color: blue;
}
.button-plain {
background: none;
color: gray;
text-decoration: underline;
}
In this example, the class button-primary
and button-plain
suggest that they inherit properties from the button
class, but for them to actually inherit those properties they must be used together in the markup:
<a class="button button-plain”>Cancel</a>
Clearly, this is redundant, but, fortunately, there’s a way to move the inheritance out of the markup and back into our CSS where it belongs.
CSS Inheritance in CSS
We can move the inheritance to CSS with the attribute selector. The attribute selector allows us to apply the base button properties to any element with a class that matches “button-“. It looks like this:
[class*=“button-“] {
/* base button properties */
}
.button-primary { ... }
.button-plain { ... }
That is effectively a very simple form of inheritance within CSS. Now, we can cleanup our markup by removing the extra button class:
<a class=“button-plain”>Cancel</a>
Written by Jacob Lichner
Related protips
7 Responses
Hi, nice tip!
But can you remember me the current support of [class*=""]
selector on navigators?
Thanks for the comment! Browser support is solid all the way down to IE7.
Additional question: have you some bench/perfs about this usage (vs the classical or preprocessor generated way)?
Negative… But if you would like to run some tests, let me know what you discover.
Certainly would look at using Sass and the @extend operator, rather than potentially expensive attribute selectors.
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#extend
Thanks… I use @extend extensively.
The quotation marks in your code are invalid. This has caused problems for folks copy-pasting to try it out.
See: https://stackoverflow.com/questions/67842959/css-inheriting-or-sharing-properties-class-inheritance-in-css