简体   繁体   中英

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. They both have the same rule for some class.

Is it possible to use one of them on some html element, and to use the other on another html element?

For example, let's say I have these external css files:

light.css:

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

.nice-color {
    color: black;
}

and I have 2 html elements:

<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?

I'm open to ideas like splitting the html file, using Angular, etc.

I think you're looking for scoped CSS . It'll allow you to include different CSS for different sections of your HTML.

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.

You have 2 ways of going about this.

  1. Load only the css that you need. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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