I am building a widget that will be displayed on a client's site. We cannot use an iFrame so I am forced to use an exhaustive CSS reset (https://github.com/premasagar/cleanslate) to avoid interference with their styles. To use that solution, I need to add !important to all of my styles and because there are a lot of them and I want to keep this code easy to maintain, I'm looking for a more dynamic solution.
I am able to add !important to the stylesheet via javascript but that's not ideal for a production environment. I am using CodeKit and LESS and wondering if either of these are able to help me easily add !important to all styles when the CSS file is generated.
Mixin? CodeKit config?
I hate using !important
except in the most extreme circumstances. Most people use it like a chainsaw when they should be using a scalpal to do the job. Nevertheless, I understand the issues facing widget developers like yourself, and your choice to use https://github.com/premasagar/cleanslate leaves you with no option.
Marc's answer noted a good feature of LESS, but he failed to demonstrate how that can help in this matter.
If you wrap your entire LESS code in a namespaced mixin, then this feature does exactly what is needed. So assume your widget code looked like this (you mentioned you are already using some type of class for your widget):
.yourWidgetClass div > p {
prop: something;
&:hover {
prop: some-hover-style;
}
}
.yourWidgetClass .someClass {
prop: something;
}
Then you can do this (wrapping all your widget code in #makeImportant()
then calling that mixin with the !important
feature noted in Marc's answer):
#makeImportant() {
.yourWidgetClass div > p {
prop: something;
&:hover {
prop: some-hover-style;
}
}
.yourWidgetClass .someClass {
prop: something;
}
}
& {
#makeImportant() !important;
}
This produces the following CSS Output:
.yourWidgetClass div > p {
prop: something !important;
}
.yourWidgetClass div > p:hover {
prop: some-hover-style !important;
}
.yourWidgetClass .someClass {
prop: something !important;
}
For my original (accepted) answer that was way more manually intensive, see the edit history.
I found that LESS can mark all properties set by a mixin at once as !important
when specify !important
after the mix-in call.
.someMixin() {
background-color: #fff;
cursor: pointer;
}
.someUsages {
.someMixin() !important;
}
Results in:
.someUsages {
background-color: #fff !important;
cursor: pointer !important;
}
For more information on this topic see the LESS doc about "The !important keyword".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With