Tech Junkie Blog - Real World Tutorials, Happy Coding!: CSS: inherit and initial Keywords

Wednesday, August 14, 2019

CSS: inherit and initial Keywords

There are certain keywords in CSS that works on a global scale and inherit is one of them.
The keyword inherit simply means that current element inherit the properties of it's parent element.
It is applied automatically be default, but it could be useful when you want to be specific about what you want.

For example if you define the following style for the parent element

#parentElem {color: red; font-weight: bold}

And have the following markup, the style will automatically be applied to the child element

        <div id="parentElem">
            <p>Child element</p>
        </div>











That's all great an all if its what you wanted, but what if you want some control over the child element.  What if you wanted to inherit the font-weight but not the color.  Well you can set the color property to initial, and the font-weight to inherit and reset the property its initial value.  That means the color will not be inherited, and the font-weight will be inherited from the parent.

.childElem {color:initial; font-weight:inherit}

If you have the following HTML markup you will see the following

        <div id="parentElement">
            <p class="childElem">Child element</p>
        </div>









As you can see the color is no longer red for the child element, but it's still bold because its inherited from the parent.

If you want to set the child font color to another color, you can set the property again to set the color.

Like the following:

            .childElem {color:initial; color: blue; font-weight:inherit}

The following will be the output








Here is the entire markup:


<html>
    <head>
        <style>
            #parentElement {color: red; font-weight: bold}
            .childElem {color:initial; color: blue; font-weight:inherit}            
        </style>
    </head>
    <body>
        <div id="parentElement">
            <p class="childElem">Child element</p>
        </div>
    </body>
</html>

Previous: CSS Stretch And Condense Fonts With font-stretch

No comments:

Post a Comment

Search This Blog