Using !important in your media queries
We sometimes hear people arguing that we shouldn’t use !important
in our website’s CSS as it can be incredibly annoying for others who may work on the website. While I agree with this in general, I have found myself using !important
with responsive design.
Back in , Louis Lazaris wrote an article on the !important
CSS declaration and when to use it. It’s a thorough article and I agree with the points it contains.
In his article, Louis proved a number of situations where !important
might be used:
- To aid or test accessibility
- To temporarily fix an urgent problem
- To override styles within Firebug or another developer tool
- To override inline styles in user-generated content
- For print stylesheets
- For uniquely-designed blog posts
To this list I would add another item:
- To override styles from within media queries
Since the styling that you will place within your media queries is intended to override previous styling when certain conditions are met, depending on the complexity of the previous styles, overriding with !important
can be an ideal and neater solution.
For example, in this contrived example, if the main stylesheet contained styles such as the following:
.content .teaser {
background:#aaa;
padding:0;
}
.content .teaser.main {
width:60%;
background:#ddd;
float:left;
}
.content .teaser.other {
width:40%;
float:right;
}
.content .box .teaser.main {
width:75%;
}
.content .box .teaser.other {
width:25%;
background:#eee;
}
And you wanted to override this on a “mobile” layout, instead of writing:
@media only screen and (max-width:28.125em) {
.content .teaser.main, .content .teaser.other, .content .box .teaser.main, .content .box .teaser.other {
width:100%;
background:#ccc;
float:none;
}
}
You could make use of !important
and simply write:
@media only screen and (max-width:28.125em) {
.content .teaser {
width:100% !important;
background:#ccc !important;
float:none !important;
}
}
Granted that the difference isn’t that great in this contrived example, but I think you see what I’m getting at.
Are any of you using !important
in your media queries? Are any of you against the idea?