Override a CSS Class Style
If someone wants to override a class style (like .responsive-style th
), they can use CSS with higher specificity, the !important
declaration, or inline styles. Here’s how each method works ...
1. Using Higher Specificity
By creating a more specific selector, you can override the .responsive-style th
styles.
div.responsive-style th {
border: 3px solid #f00; /* Overrides .responsive-style th */
}
This selector is more specific because it includes an element (div
) in addition to the class and type selector. The specificity is 0-1-2, compared to .responsive-style th
's 0-1-1, so it wins.
If you want even more specificity, you can stack classes or elements:
html body div.responsive-style th {
border: 3px solid #f00;
}
2. Using the !important
Declaration
The !important
declaration forces a style to apply, regardless of specificity or the order in which the CSS is defined.
.responsive-style th {
border: 1px solid #ddd; /* Original style */
}
th {
border: 3px solid #f00 !important; /* Overrides all styles */
}
Caution: Overusing !important
can make your CSS harder to manage and debug, so use it sparingly and only when necessary.
3. Using Inline Styles
Inline styles applied directly to an element have the highest specificity and override any external or internal stylesheet.
<th style="border: 3px solid #f00;">Name</th>
This will override all .responsive-style th
or global th
styles because inline styles have the highest precedence.
4. Combination of !important
and Inline Styles
Even if .responsive-style th
uses !important
, you can override it by applying !important
to an inline style:
<th style="border: 4px solid #0f0 !important;">Name</th>
This will override everything, including other !important
declarations.
Best Practices
- Use higher specificity for clean, maintainable CSS.
- Use
!important
as a last resort when dealing with stubborn styles. - Use inline styles only for one-off, dynamic cases where CSS cannot be applied effectively.
For maintainability, always consider re-evaluating your CSS architecture before resorting to !important
or inline styles.