html

Can a CSS Class Inherit One or More Other Classes

HTML and CSS are not coding languages. They both are markup languages. The HTML elements can have class attributes accessed in CSS for styling purposes. These CSS classes can inherit one or more other CSS classes. This can be done in the “LESS“, a backward-compatible CSS language extension, which stands for Leaner Style Sheets.

This write-up will describe how to inherit one or more CSS classes to a CSS class.

Can a Class in CSS Inherit One or More Other Classes?

A class in CSS can inherit one or more other classes using tools such as Leaner Style Sheets. It offers additional features that help in developing the application easily.

For a practical demonstration, check out the example below.

HTML

In HTML, add two “<div>” elements with the classes “section” and “sub-section” respectively:

<div class="section">Section</div><br>

<div class="sub-section">sub-section</div>

Output

Create a LESS stylesheet by adding the “.less” extension.

Create Style.less File

First, declare two CSS classes, “common-styles” and “para”. Then, apply these classes to the HTML elements.

Style “common-styles” Class

.common-styles{

background-color: rgb(228, 225, 148);

border: 5px solid rgb(213, 213, 243);

padding: 10px;

font-size: 25px;

margin: 5px;

width: 500px;

}

The “common-styles” class is styled with the following CSS properties:

  • background-color” determines the element’s background color.
  • border” adds the element’s border.
  • padding” adds space around the element’s content.
  • font-size” indicates the font size.
  • margin” produces space around the element.
  • width” determines the element’s breadth.

Style “para” Class

.para{

font-family: fantasy;

font-size: 20px;

color: gray;

}

Here:

  • font-family” adjusts the font style.
  • font-size” sets the font size.
  • color” sets the font’s color.

Inherit CSS Class

In the below CSS section, two CSS classes are inherent by the “section” class:

.section{

.para;

.common-styles;

}

Here, one CSS class, “common-styles” is inherited to the “sub-section” class:

.sub-section{

.common-styles;

}

Output

In this way, the CSS class can inherit one or more CSS classes.

Conclusion

The CSS class can inherit one or more CSS classes using tools such as LESS. To do so, first, create an HTML file. Specify the HTML elements within it and assign them the classes. In the LESS file, declare the classes with CSS properties. To inherit styles, specify the class within the curly brackets of the other class. This post has explained how one or more classes are inherited by a CSS class.

About the author

Nadia Bano

I am an enthusiastic and forward-looking software engineer with an aim to explore the global software industry. I love to write articles on advanced-level designing, coding, and testing.