Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why css variables override another file's css variable?

When I define a variable in various CSS files, and include these files in my HTML file, then it overrides the previous variable. Why is it happening?

Let's say that I have

test1.css

:root {
    --size-of-font: 5rem;
 }
.logo{
    font-size: var(--size-of-font);
}

test2.css

:root {
--size-of-font: 1.2rem;
}
.outer {
    font-size: var(--size-of-font);
    cursor: pointer;
    text-align: center;
}

test.html

<link rel="stylesheet" href="test1.css">
  <link rel="stylesheet" href="test2.css">

<div class="outer">
    <h1 class="logo">Lorem Ipsum</h1>
     <p>Neque porro quisquam est qui dolorem 
          ipsum quia..."<br>
          "There is no one who loves pain 
          itself..."
     </p>
</div>
like image 281
P.Bora Avatar asked Oct 15 '25 20:10

P.Bora


2 Answers

CSS = Cascading Style Sheets... this means the sequence of definition matters, the most recent and more specific takes precedence. If you switched test1 and test2 over in your html you'd get a different result because the variable is defined as the more recent value.

I recommend you use a different variable name for your different .css files if you require them to not share this value.

like image 161
SazooCat Avatar answered Oct 18 '25 13:10

SazooCat


When you include both stylesheets, all of their rules are combined into one single stylesheet. This means that you introduce a conflict in two :root CSS rules with the same custom property declaration:

:root {
  --size-of-font: 5rem;
}

:root {
  --size-of-font: 1.2rem;
}

Cascade resolution means that the specified value of the --size-of-font custom property is 1.2rem, not 5rem. Simply, the second declaration overrides the first as both rules have identical selectors.

This value of 1.2rem is then applied to both uses of var(--size-of-font), in .logo and .outer, again because two stylesheets combine to form one. .logo does not only see the --size-of-font in its own stylesheet; it sees whatever is resolved by the cascade, taking all declarations into account.

like image 37
BoltClock Avatar answered Oct 18 '25 12:10

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!