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

CSS Grid Layout v CSS Frameworks

Should you be using a CSS Framework to build your grid or should you use the native CSS Grid Layout?

Nov 15, 2018

Full-Size, Looping Background Video with YouTube Video

It seems looping background videos are the new thing. But you don't have to serve up the video on your server. Let's use a YouTube video to accomplish it!

Feb 12, 2016

A Simple CSS Build Pipeline Using PostCSS

PostCSS is a super powerful tool that can help you craft your own CSS build pipeline. But it can be a lot to take in all at once. Here are a few quick steps to getting started with PostCSS.

Jun 03, 2021