😄 This post is based on the content from coding.courses.
!important Declaration
When defining CSS styles, certain properties may be critical enough to require precedence over others. In such cases, the !important keyword is used to indicate that a specific declaration carries more weight than a standard property: value;.
In CSS, this is known as an important declaration. It is implemented by adding !important before the semicolon (;) at the end of a declaration, as in property: value !important;.
When !important is applied to a property value, it overrides the standard cascade rules, causing the specified value to take precedence over other declarations.
Overriding Style Priority
<style>
#myid {
background-color: red;
}
.important-background {
background-color: yellowgreen !important; /* !important declaration */
}
</style>
<p id="myid" class="important-background">
CSS !important Usage – Overriding Style Priority
</p>
As shown in the demo above, although the #myid selector has higher specificity than .important-background, the value of the background-color property is applied as yellowgreen.
This occurs because the !important declaration overrides the cascade, causing the specified property value to take precedence over other declarations.
Things to Watch Out For
# Multiple !important Declarations on the Same Property
<style>
#myid { /* specificity = 0,1,0,0 */
background-color: red !important;
}
.important-background { /* specificity = 0,0,1,0 */
background-color: yellowgreen !important;
}
</style>
<p id="myid" class="important-background">
CSS !important Usage – Overriding Style Priority
</p>
As shown in the example above, when multiple !important declarations are applied to the same property of the same element, they are assigned equal importance. In this case, standard cascade rules apply, and the value from the selector with higher specificity is used.
# Prohibition Inside @keyframes Blocks
The !important declaration is ignored when used within @keyframes blocks.
<style>
.important-background {
animation: bg-animation 3s infinite both;
}
@keyframes bg-animation {
0% {
background-color: red !important;
}
100% {
background-color: yellowgreen;
}
}
</style>
<p class="important-background">
CSS !important Usage – Overriding Style Priority
</p>
In the example above, background-color: red !important; is defined inside a @keyframes block. In this context, the !important keyword is ignored, and the declaration behaves as a normal property assignment.
Consequently, the animation proceeds as expected, transitioning to background-color: yellowgreen; at the 100% mark.
When Should You Use !important?
- Overriding inline styles that cannot be modified.
- In particular, when CSS is applied via JavaScript using the style attribute, it is treated as an inline style. In such cases, using !important is useful when you want to prevent those styles from being overridden.
- Overriding highly specific CSS rules when no better alternative exists.
Top comments (0)