!important is Important

The !important declaration has really bad reputation, and deservedly so. As is often the way, this reputation results from abuse rather an inherent problem with the property itself. An example of its abuse might be:

#nav {
  float: none !important;
  /* where did I float this? */
}
/* ...jumble of code... */
ul#nav {
    float: left;
}

There are, however, instances where the !important declaration is the best tool for the job.

Responsive Web

The increase of users accessing web sites via mobile devices has redefined the way many design for the web. Rather than considering the desktop first, they now consider the mobile user. Andy Clarke’s 320 and Up is one reaction to this.

A requirement of the responsive web is that images expand and contract according to the width of the browser. To achieve this, the advice to define the width and height in the HTML has been reversed, an image should now be added without these attributes.

<img src="img.png" width="30" height="30" />

This leads to problems when redesigning a site, images in previous blog posts and older content could have the width and height defined. If the site uses a CMS with a visual editor, it may add the dimension to an image by default and content editors may unwittingly break the layout by leaving them in place.

To allow for this, I usually add the following to the CSS

img {
  height: auto !important;
  max-width: 100% !important;
}

Print Styles

There are certain elements that are almost always hidden from print styles: skip links, navigation, and oversized footers, for example. Backgrounds are also removed as they’re not printed by default. Changes to the screen layout won’t alter these needs. To avoid future problems, it is legitimate to include the following in your style sheet:

@media print {
  #nav, #footer, .sidebar {
    display: none !important;
  }
  .has-a-background {
    background: #fff !important;
  }
}

Update 16 Nov, 2011: changed img code block.

By Peter Wilson

Peter has worked on the web for twenty years on everything from table based layouts in the 90s to enterprise grade CMS development. Peter’s a big fan of musical theatre and often encourages his industry colleagues to join him for a show or two in New York or in the West End.

2 comments

  1. Also sometimes to override plugin styles as well (to avoid styles breaking with plugin upgrades). Seems like plugin developers are getting better at putting their styles in external files now that don’t get overwritten with upgrades.

Comments are closed.