DEV Community

Cover image for CSS variable chapter seven "inheritance" 🛵️
🚩 Atul Prajapati 🇮🇳
🚩 Atul Prajapati 🇮🇳

Posted on Edited on

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;
}
💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน 💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน

we can add or create a new CSS variable based on existing CSS variable like 🥑

--duplicate-red: var(--red);
💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน 💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน

So our final variable looks something like this🥞

:root {
    --red: #ff6f69;
    --beige: #ffeead;
    --yellow: #ffcc5c;
    --duplicate-red: var(--red);
}
💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน 💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน

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;
}
💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน 💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน

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;
}
💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน 💬 ชาวเน็ตแห่แชร์: atulcodex/css variable chapter seven inheritance ep - ประเด็นร้อน

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)