Home

CSS !important - What is it?

Learn what the !important flag does in CSS.

There are two important points to note regarding how a CSS (Cascading Style Sheet) is read.

First, they  cascade. But what the heck does that mean? Let's say you have this code in your stylesheet:

div {
background-color: #000;
}

div {
background-color: #fff;
}

The sheet is read from the top down, so if there are conflicting styles, then the one lower in the sheet takes precedence. So in this  case, your divs' background color will be white (#fff). In a similar case, HTML files are read top-down, so if you have this code in your HTML file:

<link rel="stylesheet" type="text/css" href="stylesheet-1.css" />
<link rel="stylesheet" type="text/css" href="stylesheet-2.css" />

then, with any conflicting styles, those in stylesheet-2.css will take precedence.

The second important note is that styles with higher specificity take precedence. Again, what the heck does that mean? Specificity goes in the order of elementclass > ID. So, let's say this code exists in your HTML file:

<div id="this-div" class="all-divs">
<span id="this-span" class="all-spans">What size is this font?</span>
</div>

And you have these styles in your CSS file:

div {
font-size: 12px;
}

div span {
font-size: 13px;
}

#this-span {
font-size: 14px;
}

.all-spans {
font-size: 15px;
}

.all-divs {
font-size: 16px;
}

What size will the font be? It will be 14px because the span ID holds the highest specificity.

But if your CSS reads this instead:

div {
font-size: 12px !important;
}

div span {
font-size: 13px;
}

#this-span {
font-size: 14px;
}

.all-spans {
font-size: 15px;
}

.all-divs {
font-size: 16px;
}

Your font size will be 12px. The !important note overrides all styles, even if they conflict, even if they are more specific. Of course, if there are two !important notes on conflicting classes, then the regular CSS rules take place.

So now that you know what it means, when would you use it? I think this post over at CSS Tricks has some good use cases.

Let's Connect

Keep Reading

Styling Placeholders for Select Fields

A (limited) CSS-only approach for styling placeholders, along with a way to work around the limitations with a custom JS-based solution.

Jun 16, 2022

WTF is CSS?

A brief description of CSS, before suggesting a couple free courses.

Jun 25, 2020

Complete Guide to Getting Started with CSS

A handful of tips and tricks on getting started with CSS to make your website visually interesting.

Pratham
Jan 27, 2022