HTML and CSS Reference
In-Depth Information
Importance
Sometimes, a declaration is so important that it outweighs all other considerations. CSS
calls these
important declarations
(for obvious reasons) and lets you mark them by
inserting
!important
just before the terminating semicolon in a declaration:
p.dark {color: #333 !important; background: white;}
Here, the color value of
#333
is marked
!important
, whereas the background value of
white
is not. If you wish to mark both declarations as important, each declaration will
need its own
!important marker
:
p.dark {color: #333 !important; background: white !important;}
You must place
!important
correctly, or the declaration may be invalidated.
!impor
tant
always
goes at the end of the declaration, just before the semicolon. This placement
is especially important—no pun intended—when it comes to properties that allow
values containing multiple keywords, such as
font
:
p.light {color: yellow; font: smaller Times, serif !important;}
If
!important
were placed anywhere else in the
font
declaration, the entire declaration
would likely be invalidated and none of its styles applied.
I realize that to those of you who come from a programming background, the syntax
of this token instinctively translates to “not important.” For whatever reason, the bang
(
!
) was chosen as the delimiter for important tokens, and it does
not
mean “not” in
CSS, no matter how many other languages give it that very meaning. This association
is unfortunate, but we're stuck with it.
Declarations that are marked
!important
do not have a special specificity value, but are
instead considered separately from non-important declarations. In effect, all
!impor
tant
declarations are grouped together, and specificity conflicts are resolved relatively
within that group. Similarly, all non-important declarations are considered together,
with property conflicts resolved using specificity. In any case where an important and
a non-important declaration conflict, the important declaration
always
wins.
Figure 2-2
illustrates the result of the following rules and markup fragment:
h1 {font-style: italic; color: gray !important;}
.title {color: black; background: silver;}
* {background: black !important;}
<h1 class="title">NightWing</h1>
Figure 2-2. Important rules always win