CSS
Web Development
Programming
CSS Inheritance
Web Design

Can a CSS class inherit from another class?

Codemia Knowledge Hub ·

No. CSS has no direct way for one class to inherit the styles of another, the way classes inherit in object-oriented languages. You can get the same effect by applying several classes to one element, by using combined selectors, or by using a preprocessor such as Sass with @extend.

What inheritance means in CSS

In CSS, inheritance runs from parent elements to child elements. If a parent sets color, its children inherit that color unless they set their own.

Class-to-class inheritance is not supported. Instead, CSS cascades: styles apply according to specificity and their order in the stylesheet.

Ways to reuse one class's styles in another

1. Put multiple classes on the element

The simplest approach is to give the element several classes, each defining part of the styling, so they combine into the final look:

html
<div class="baseclass theme boldtext">Hello World</div>

Here baseclass, theme and boldtext could handle layout, color and font weight respectively.

2. Combine selectors

You can target elements that carry a base class plus a modifier class, so the modifier adds its own styles on top of the base:

css
1.baseclass {
2    color: blue;
3    font-size: 14px;
4}
5
6.baseclass.important {
7    font-weight: bold;
8}

An element with <div class="baseclass important"> gets a 14px font size, blue color and bold font weight.

3. Use a CSS preprocessor

Sass, LESS and Stylus add variables, nesting and mixins, which allow a form of inheritance. With Sass:

scss
1.baseclass {
2    color: blue;
3    font-size: 14px;
4}
5
6.important {
7    @extend .baseclass;
8    font-weight: bold;
9}

@extend makes .important take on the properties of .baseclass and add its own.

Comparing the techniques

TechniqueTool RequiredExample UsageBenefits
Multiple ClassesNone<div class="base theme">Simple, No extra tools needed
Combined SelectorsNone.baseclass.important &#123; ... &#125;High specificity, simple to implement
Preprocessors (@extend)Sass, LESS, etc..important &#123; @extend .baseclass&#125;Powerful, flexible and maintainable

All three reduce duplicated CSS, so styles are reused rather than repeated, changes happen in fewer places, and the stylesheet stays manageable as the project grows.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD