简体   繁体   English

HTML/CSS - 在多个样式表中保持变量

[英]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:所以我的网站运行的基本方式是有一个“base.html”和“base.css”模板,它们有一个顶部栏,分别定义了页面颜色、文本颜色等变量,如下所示:

: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.然后,其他 HTML 页面以{% extends "base.html" %}开头,然后将它们的内容插入到页面正文中。 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.我希望该表中的项目将其着色为var("--bg-primary")但是当我使用在一个样式表的根中定义的变量时,我仍然无法在另一个样式表中使用它,即使是最后一页扩展后将导入两个样式表。 Is there a way to do this?有没有办法做到这一点?

It should not matter if the CSS custom properties are declared in an external CSS file or the same file. CSS 自定义属性是在外部 CSS 文件中还是在同一文件中声明应该无关紧要。 eg例如

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测试.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:结果:

上面代码示例的结果

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.因此,它必须与您导入 css 的顺序有关 - 或者与您的页面设置方式有关。

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.另外,您还可以通过 javascript 访问/设置您的自定义属性。 eg例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM