Search code examples
htmlcss-variables

HTML/CSS - Keep Variable Across Multiple Stylesheets


So the basic way my website functions is that there is a "base.html" and "base.css" template which has a top bar and defines the variables of page color, text color, etc. respectively, like this:

:root {
--text-primary: #b6b6b6;
--text-secondary: #5f5f5f;
--bg-primary: #23232e;
--bg-secondary: #141418;
}

Then, the other HTML pages start with {% extends "base.html" %} and then insert their content into the body of the page. Each of these other pages will also import a stylesheet. For example, one page uses a table to show different options. I want that table to have the items in it colored to var("--bg-primary") but when I use a variable defined in the root of one stylesheet, I still can't use it in another even though the final page after extends will have both stylesheets imported. Is there a way to do this?


Solution

  • It should not matter if the CSS custom properties are declared in an external CSS file or the same file. e.g.

    global.css

    :root {
    --text-primary: #b6b6b6;
    --text-secondary: #5f5f5f;
    --bg-primary: #23232e;
    --bg-secondary: #141418;
    }
    

    style.css

    .primary {
        color: var(--text-primary);
    }
    .secondary {
        color: var(--text-secondary);
    }
    .bg-primary {
        background-color: var(--bg-primary);
    }
    .bg-secondary {
        background-color: var(--bg-secondary);
    }
    

    test.html

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <link href="global.css" rel="stylesheet">
            <link href="style.css" rel="stylesheet">
        </head>
        <body>
            <div class="primary">foo</div>
            <div class="secondary">bar</div>
            <div class="bg-primary">baz</div>
            <div class="bg-secondary">bat</div>
        </body>
    </html>
    

    result:

    result of the above code example

    So it has to be to do with either the order you are importing your css - or else something else to do with how your page is set-up.

    So to answer you question: Is there a way to do this? Yes - that is how they work out of the box.

    As an aside you can also access/set your custom properties via javascript. e.g.

    getComputedStyle(element).getPropertyValue("--text-primary");
    element.style.setProperty("--text-primary", "#f0f0f0");