Understanding the Impact of !important in CSS

The !important keyword upends some of these rules. When a declaration contains an !important keyword, that declaration takes precedence, regardless of specificity or cascade rules. Consider the following CSS:

body {

background: pink (important;

}

html body {

background: yellow;

}

Although html body has a higher level of specificity (0,0,2) than body (0,0,1), the !important keyword means that our document will have a pink background instead of a yellow one.

Overriding an !important declaration requires another !important declaration paired with a selector of equal or higher specificity. In other words, if we really wanted a yellow background, we’d need to add an !important keyword to the htmL body rule set.

Removing the body rule altogether is also an option. If you have complete control over your stylesheets and markup, doing so would save a few bytes. If you’re using a component library, or customizing a theme, you may prefer to override the rule instead. That way, your changes won’t be undone by a new release of the component or theme.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *