Reputation: 59
Provided I have two different css files, each containing a definition of the same css class (Eg. .mainDiv {}
) but each class would have different properties, how would I be able to apply them to two different divs in my HTML code (say with ids myMainDiv1
and myMainDiv2
)?
I realize this is no longer an association between div element ids and css classe names but I would like to know if it is possible somehow to parse/read each css file - through JavaScript - and apply the rules dynamically for each of my divs.
So I would in no way want to make changes to the css files; I can have as many as needed but they all need to have the very exact same class names (Eg. mainDiv
); through JavaScript - if possible - I can apply the styles for each of my divs.
Upvotes: 1
Views: 1698
Reputation: 2444
It is really not a good idea to try and parse your CSS using javascript, instead just use CSS for what it's very good at, selectors.
The best option is to prefix every rule in each file. So if you have light-theme.css
and dark-theme.css
then every rule in light-theme.css
would start with something like .light-theme
(and the same goes for dark-theme.css
-> .dark-theme
).
Once each rule is prefixed accordingly you can include both files and just add a class based on which CSS file you want to take effect.
/* Shared styles */
#content {
height: 400px;
width: 400px;
}
#content > div {
width: 200px;
float: left;
}
ul {
list-style: square inside;
}
li {
height: 40px;
}
/* light-theme.css */
.light-theme li {
color: #339;
background-color: #fff;
}
/* dark-theme.css */
.dark-theme li {
color: #ccf;
background-color: #333;
}
<div id="content">
<div class="light-theme">
<h2>Light</h2>
<ul>
<li>Red</li>
<li>White</li>
<li>Blue</li>
</ul>
</div>
<div class="dark-theme">
<h2>Dark</h2>
<ul>
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
</ul>
</div>
</div>
Upvotes: 1
Reputation: 144
You can give multiple classes to an element. If you are using a class mainDiv
<div class="mainDiv firstMainDiv"></div>
<div class="mainDiv secondMainDiv"></div>
now the styles given with class name .mainDiv will apply on both. But if you want to give some styles specifically to first div then you can use both classes
.mainDiv.firstMainDiv {}
this styles will apply only in first div.
Upvotes: 0
Reputation: 61083
You'd have to override the incorrect styles with more specific selectors.
#myMainDiv1.mainDiv { ... }
#myMainDiv2.mainDiv { ... }
Upvotes: 0