DEV Community

Cover image for CSS variable chapter seven "inheritance" ๐Ÿ›ต๏ธ

CSS variable chapter seven "inheritance" ๐Ÿ›ต๏ธ

Hello party people๐Ÿ‘‹

First of all, thank you for your love and support till this moment, now we have 1K follows at this DEV community๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘

Thank you

In the last dev post, we have learned about "how we can use CSS variable in responsiveness" and in this post, we are going to understand a short confusion of CSS variable which is inheritance๐ŸŒบ

โ˜ƒ๏ธ So to understand inheritance, let's create a CSS global variable named ":root" which like this.

:root
{
    --red: red;
    --blue: blue;
    --yellow: yellow;
}
Enter fullscreen mode Exit fullscreen mode

we can add or create a new CSS variable based on existing CSS variable like ๐Ÿฅ‘

--duplicate-red: var(--red);
Enter fullscreen mode Exit fullscreen mode

So our final variable looks something like this๐Ÿฅž

:root {
    --red: #ff6f69;
    --beige: #ffeead;
    --yellow: #ffcc5c;
    --duplicate-red: var(--red);
}
Enter fullscreen mode Exit fullscreen mode

If you understand CSS variable, you know that we can use --duplicate-red property as a ---red color property๐Ÿฅ˜

But now when I will try to override our --red variable at our navbar selector like this.

#navbar 
{
    --red: orange;
}
Enter fullscreen mode Exit fullscreen mode

it will not work :( because at this position our --duplicate-red property is resolved as the value of --red . It means we can't reinitiate or override the --red property.

But we can override our --duplicate-red like this

#navbar 
{
    --duplicate-red: orange;
}
Enter fullscreen mode Exit fullscreen mode

And it will work well because our computer machine read it like a new variable.

๐Ÿงญ At this stage of the post I recommend you to play around with this codepen project, it will help your muscle memory to understand.

That's all for this post and if you have any queries please comment below I love ๐Ÿ’– to hear from you ๐Ÿ™…๐Ÿปโ€โ™‚๏ธ

Top comments (0)