简体   繁体   English

在两个不同的元素上应用来自两个不同 css 文件的相同 css 规则

[英]Apply same css rule from two different css files on two different elements

I wonder if the following is possible.我想知道以下是否可能。

I have 2 external css files that I want to use and can't change.我有 2 个外部 css 文件,我想使用但无法更改。 They both have the same rule for some class.对于某些 class,它们都有相同的规则。

Is it possible to use one of them on some html element, and to use the other on another html element?是否可以在某些 html 元件上使用其中一个,而在另一个 html 元件上使用另一个?

For example, let's say I have these external css files:例如,假设我有这些外部 css 文件:

light.css:

.nice-color {
    color: white;
}
dark.css:

.nice-color {
    color: black;
}

and I have 2 html elements:我有 2 个 html 元素:

<div class="nice-color"></div>
...
<div class="nice-color"></div>

Can I somehow apply the light.css on the first element, and apply the dark.css on the second one?我可以以某种方式在第一个元素上应用 light.css,在第二个元素上应用 dark.css 吗?

I'm open to ideas like splitting the html file, using Angular, etc.我愿意接受诸如拆分 html 文件、使用 Angular 等的想法。

I think you're looking for scoped CSS .我认为您正在寻找范围 CSS It'll allow you to include different CSS for different sections of your HTML.它允许您为 HTML 的不同部分包含不同的 CSS。

Example:例子:

<div>
    <style scoped>
        p { font-weight: bold }
    </style>
    <p>This is bold</p>
</div>
<p>This is regular weight</p>

Personally, I don't think it's a very good pattern to use, but I'm sure there are some good use cases out there for it, particularly if you've only got the ability to insert your HTML in a specific part of a website.就个人而言,我认为这不是一个很好的使用模式,但我确信有一些很好的用例,特别是如果你只能将 HTML 插入到特定部分网站。

You have 2 ways of going about this.你有两种方法可以解决这个问题。

  1. Load only the css that you need.仅加载您需要的 css。 If you're using dark theme, then load only that.如果您使用的是深色主题,则仅加载该主题。 vice versa for light theme.反之亦然,用于轻主题。
  2. Add a class / id to the body so that you can change css easily.将 class / id 添加到正文中,以便您可以轻松更改 css。

ie. IE。

#dark .nice-color {
   color: white
}

#light .nice-color {
   color: black
}

<body id="dark">
   <p class="nice-color">Something here</p>
</body>

If you're willing to use less or sass it could be simplified如果您愿意使用更少或 sass 可以简化

#dark {
   .nice-color {
        color: black;
    }
}

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

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