Reputation: 4147
I am trying to organize and structure our applications better with LESS and I'd like to know the best route in doing a task using "!important". Currently we have a lot of these and I'd like to get rid of them if it makes sense. My example is:
<div id="test">
<ul>
<li>One</li>
<li>Two</li>
</ul>
</div>
<button id="button">
Select
</button>
$('#button').on('click', function(){
$('#test li').toggleClass('blue');
})
Option 1:
#test {
ul{
li{
color: red;
}
.blue{
color: blue;
}
}
}
So with LESS, if I have the class after the initial color, it should over take. If I want to add the blue class, then I would insert it into each area within the LESS file, or do:
Option 2:
#test {
ul{
li{
color: red;
}
}
}
.blue{
color: blue !important;
}
In this case I would have it listed once, and then whenever it is called it will override the class. Or have an Option 3 if someone thinks there is something better than these two. I'm not sure what the best route is, but I'd like to get rid of !important if possible.
Upvotes: 0
Views: 198
Reputation: 4687
I subscribe to the view that you should only use !important
as a temporary fix while you refactor your styles. Clearly you have a specificity problem to address (which your example doesn't quite demonstrate). In your example, I would first do Option #2 (if it was hard enough to figure), then refactor overrides like .blue
into a style which is loaded last.
https://jsbin.com/cekobodixe/edit?html,css,js,output
If we change it slightly we reach a common problem: the use of id doesn't allow cascading precedence by load order:
https://jsbin.com/xikolenevo/1/edit?html,css,js,output
and so that suggests a second factor to the fix, replacing ids with classes.
Another thing that might happen is that a set of rules for a specific component were added to an override stylesheet instead of to the component. So now, the rules are overriding otehr components as well. The solution here is to relocate the offending styles to their respective components. This can get ugly fast, so its best to do this early.
Upvotes: 2
Reputation: 275
The only thing I could think of is making two different classes, one red and one blue. Set the li objects in your html to .red and changing the class on click. But I don't think that's a very pretty solution. Otherwise I think you have to stick to your !important.
Upvotes: 0