Given the <style>
I wrote, I expected the 1st <h1>
and 2nd <h1>
to have same font-size
, but it is not true:
:root {
--default-size: calc(1rem + 0.5vw);
font-size: var(--default-size);
}
.font-size\:default {
font-size: var(--default-size) !important;
}
<h1>DIMENSION</h1>
<h1 class="font-size:default">DIMENSION</h1>
Digging around, I found this comment on stackoverflow https://stackoverflow.com/a/48415933/7253377 , and the problem seems related to how var() are evaluated, or better, when they are evaluated by the browser.
So, I wrote this simple snippet and it seems to work correctly:
:root {
--default-size: calc(1rem + 0.5vw);
}
* {
font-size: var(--default-size);
}
.font-size\:default {
font-size: var(--default-size) !important;
}
<h1>DIMENSION</h1>
<h1 class="font-size:default">DIMENSION</h1>
The only problem is that I don't think to get at 100% what is going on. The 1st approach didn't work because:
- The :root var() is evaluated when the :root is rendered.
- The * var() is evaluated when any element is rendered.
- The .font-size:default var() is evaluated when an element with this class is rendered
And the :root var() value happens to be different from the .font-size:default var() value? If yes, why?