Can a CSS class inherit one or more other classes?
In pure CSS, there is no direct mechanism by which one class automatically “inherits” styles from another class. Each CSS class is simply a selector with its own declarations. That said, you can simulate a form of “inheritance” by:
- Applying multiple classes to the same HTML element, so the styles from both classes are combined.
- Using preprocessors (like Sass with
@extend
) to reuse or extend existing rules. - Leveraging common selectors (e.g.,
.classA, .classB
sharing declarations).
Below are some details.
1. No Native Inheritance for Classes in Plain CSS
In CSS, classes don’t have an “is-a” or inheritance relationship. They’re just selectors that apply styles to matching elements. If you write:
.superClass { color: blue; } .subClass { /* Can't say "inherit from .superClass" here in plain CSS */ background: yellow; }
The browser doesn’t have a way to interpret “.subClass inherits .superClass.” Each class stands alone.
2. Combine Classes on an Element
You can have an HTML element belong to multiple classes. For example:
<div class="superClass subClass">I get styles from both .superClass and .subClass</div>
- The styles from
.superClass { ... }
and.subClass { ... }
both apply. - But this is not “class inheritance”—it’s just the element matching multiple selectors simultaneously.
3. Preprocessors: Sass/SCSS @extend
Some CSS preprocessors offer a feature that mimics inheritance. In Sass (SCSS syntax):
.superClass { color: blue; background: lightgray; } .subClass { @extend .superClass; // "inherits" all .superClass properties border: 1px solid red; }
The compiled CSS might look like this:
.superClass, .subClass { color: blue; background: lightgray; } .subClass { border: 1px solid red; }
So it’s effectively merging .subClass
with .superClass
in the final, generated CSS. However, this isn’t standard CSS—it’s a feature of Sass (or Less, or Stylus). Once compiled, you get plain CSS with multiple selectors.
4. Common Selectors
If you want multiple classes to share some styles, you can define a common block of rules and reference them with a comma:
.superClass, .subClass { color: blue; background: lightgray; } .subClass { border: 1px solid red; }
Now both .superClass
and .subClass
have the same color and background, and .subClass
has additional styles. This still isn’t inheritance in the OOP sense—just shared declarations.
Summary
- No direct class inheritance in plain CSS—each class is its own style rule.
- HTML trick: Apply multiple classes to the same element to combine their effects.
- Preprocessors like Sass allow
@extend
, which merges selectors at compile time, simulating “class inheritance.” - Comma-separated selectors let you share rule sets among multiple classes in standard CSS.
Key Takeaway
In pure CSS, classes don’t “inherit” from one another. However, you can combine classes on an element or use preprocessor features (@extend
, mixins) for more DRY, reusable styles.