- Basics
- Selectors
- Colors
- Units
- Inheritance, Specificity & Cascade
- !important and when to avoid it
- Box Model and Layout
- Display Property
- Position Property
- Flexbox
- Grid Layout
- Centering (vertical & horizontal)
- Z-index and Stacking Context
- Typography
- Visual Effects
- Responsive Design
- Animations
- Advanced CSS
- Best Practices and Accessibility
!important and when to avoid it
Learn what !important does in CSS, when to use it, and why it's best to avoid overusing it in your styles.
!important
is used to forcefully apply a CSS rule, even if other rules have higher specificity or appear later in the code.
Syntax:
selector {
property: value !important;
}
Example:
p {
color: red !important;
}
This will make all <p>
tags red, no matter what other CSS rules are written elsewhere.
Why !important works
Normally, CSS decides which rule to apply using:
- Specificity
- Source Order
- Cascade
But if you add !important
, it jumps to the top priority and overrides everything (except another !important
rule with higher specificity).
Example:
<p class="special" id="unique">This is a paragraph.</p>
p {
color: blue;
}
.special {
color: green;
}
#unique {
color: orange;
}
p {
color: red !important;
}
Even though #unique
is more specific, the red color with !important
will win.
When to Use !important
You can use !important
when:
- You want to override 3rd-party CSS (like Bootstrap or external stylesheets).
- Quick fixes for critical styles in a project.
- Utility classes where you want to guarantee a style.
Example (utility):
.text-white {
color: white !important;
}
When to Avoid !important
Avoid using !important
casually because:
- It breaks the normal flow of CSS (specificity, cascade).
- Makes your CSS hard to maintain and debug.
- Can lead to "important wars" (where you keep adding more
!important
to fix conflicts).
Better alternatives
- Increase selector specificity.
- Use better CSS architecture (BEM, utility-first).
- Avoid deeply nested selectors.
- Refactor CSS instead of forcing overrides.
Common Mistake
Bad Practice Example:
body {
background: black !important;
}
This can cause unexpected styling issues, such as overriding themes, color modes, or other critical styles.
Use !important
only when absolutely necessary.
If you’re using it often, it’s a sign to rethink your CSS structure.
In short, use !important
sparingly and only when necessary to keep your CSS manageable.