Reputation: 940
Is it possible to make the entire .class CSS selector important? I'm thinking in this kind of structure:
.custom-selector !important {
display: inline-block;
vertical-align: middle;
position: relative;
padding-left: 5px;
}
I don't know if it's possible.
Upvotes: 48
Views: 61770
Reputation: 82734
No, it's not possible. !important
is thought to be an instrument of last resort and as such should be used sparingly. !important
ing whole selectors would caricature that idea.
If you need to trump other styles, use CSS specificity to your advantage. You can use, e.g., these techniques to push your style declarations to the top:
double class name will trump single class name:
.custom-selector.custom-selector > .custom-selector
ID trumps class:
#custom-id > .custom-class
IDs can be duplicated, too:
#id#id > #id
inline styles trump any stylesheets:
<style>
p#id#id.class.class { color: green; }
</style>
<p id="id" class="class" style="color:red">I am red!</p>
New feature since 2023: CSS now has a feature called “layers”. You can define them like this:
@layer base {
h1 {
color: green;
}
}
@layer higher {
h1 {
color: red;
}
}
h1 {
color: purple;
}
The result is a purple <h1>
. Um, ... “yay!”? Doesn’t sound too useful when you first encounter it. @layer
styles are always less important than “unlayered” styles. This sounds like the absolute opposite of what was asked.
But if you start to get the hang of it, @layer
s make a lot of sense. Tailwind uses them, too, for example, and you can import styles from unsupporting frameworks into your own layers:
@import url(bootstrap.css) layer(bootstrap);
This allows you to structure your CSS from least to most important and overwrite styles in lower layers without resorting to !important
or selector trickery.
Upvotes: 59
Reputation: 910
First off !important applies to one specific declaration in a CSS rule. It doesn't apply to a class. So, "no" you can't make a class !important.
Second off, !important is just one part of CSS specificity. You can also use other ways to make a rule be a more specific rule to have precedence (such as referring to an id in the parent chain instead of just the class. When I'm writing CSS, using !important is my last possible choice - I'd much rather solve overrides with other specificity solutions. Usually, if you control all the CSS, this is pretty easy to avoid using !important. If you have to override some CSS that you don't control, then sometimes it is handy.
Check this question here for more details. As it explains things better.
Upvotes: 7