CSS – How to inheritance a class

In this post, we will see how to inheritance a class in a css file.

We start creating a web page, called Home.html, where we will put a div:

[Home.html]

<!DOCTYPE html>
<html>
    <head>
        <title>Home</title>
    </head>
<body>

<h1>Test CSS</h1>

<div style="width:20%; border: 1px solid black;  font-size: 12pt;">
    Hello World 1
</div>

</body>
</html>

Now, if we want to add another div, with a different width and different font-size, we will write a HTML code like that:

<!DOCTYPE html>
<html>
    <head>
        <title>Home</title>
    </head>
<body>

<h1>Test CSS</h1>

<div style="width:20%; border: 1px solid black;  font-size: 12pt;">
    Hello World 1
</div>
<br/>
<div style="width:40%; border: 1px solid black;  font-size: 14pt;">
    Hello World 2
</div>

</body>
</html>

If we decide to use an external css file to manage the style of the page, we will create a file called style.css and then, we will add it into Home.html:

[style.css]

.divstyle1 {
    width:20%; 
    border: 1px solid black;  
    font-size: 12pt;
}

.divstyle2 {
    width:40%; 
    border: 1px solid black;  
    font-size: 14pt;
}


[Home.html]

<!DOCTYPE html>
<html>
    <head>
        <title>Home</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
<body>

<h1>Test CSS</h1>

<div class="divstyle1">
    Hello World 1
</div>
<br/>
<div class="divstyle2">
    Hello World 2
</div>

</body>
</html>

We can see that the code inside the two CSS classes are the same, so in order to optimise the code, we can create a principal class and then we will inheritance it in other classes:

[style.css]

/* Definition of the principal class, called divstyle */
[class*="divstyle"]
{
    width:20%; 
    border: 1px solid black;  
    font-size: 12pt;
}

/* Definition of the second class, called divstyle-big  */
.divstyle-big{
    width:40%; 
    font-size: 14pt;
}

/* Definition of the third class, called divstyle-verybig  */
.divstyle-verybig{
    width:60%; 
    font-size: 20pt;
}


[Home.html]

<!DOCTYPE html>
<html>
    <head>
        <title>Home</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
<body>

<h1>Test CSS</h1>

<div class="divstyle">
    Hello World 1
</div>
<br/>
<div class="divstyle-big">
    Hello World 2
</div>
<br/>
<div class="divstyle-verybig">
    Hello World 3
</div>

</body>
</html>