build-your-own.org
BOOK
BLOG
SUBSCRIBE
build-your-own.org
prev ◄─┐
Contents
┌─► next
A Visual Guide To CSS
CHAPTER
Book info
Specificity
Which selector is more specifi
c?
9
Pt1. Language
Specifi
city
●
Classes
are more specifi
c than
tags
.
Because you add classes to mark specifi
c tags.
●
IDs
are more specifi
c than
classes
.
Because IDs are supposed to be unique.
●
Adding stuff
to a selector makes it more specifi
c.
Both
.foo .bar
,
.bar.goo
are more specifi
c than
.bar
Calculating specifi
city
0.
Ignore combinators.
1.
More
IDs
=> more specifi
c.
2.
More
classes
=> more specifi
c.
Pseudo-classes and attributes are counted too.
3.
More
tags
=> more specifi
c.
Pseudo-elements are counted too.
*
div
.foo
div
.foo
.foo
>
div
#bar
:hover
a
[href]
::after
#bar #zoo
ID
=
0
CLASS
=
0
TAG
=
0
ID
=
0
CLASS
=
0
TAG
=
1
ID
=
0
CLASS
=
1
TAG
=
0
ID
=
0
CLASS
=
1
TAG
=
1
ID
=
0
CLASS
=
1
TAG
=
1
ID
=
1
CLASS
=
2
TAG
=
2
ID
=
2
CLASS
=
0
TAG
=
0
Order of
comparison
more general
more specifi
c
Small rules
that fulfi
lls
the points.
intuitive
not so intuitive
Logical selectors are special cases
:is(
S1
,
S2
, ...)
:not(
S1
,
S2
, ...)
:has(
S1
,
S2
, ...)
The
most specifi
c argument
is added to the specifi
city.
ID
=
0
CLASS
=
2
TAG
=
0
ID
=
0
CLASS
=
2
TAG
=
1
ID
=
1
CLASS
=
1
TAG
=
0
.bar
:is
(
.foo
, div)
.bar
:not
(.foo,
p
.bar
)
.bar
:has
(.foo,
#goo
)
.bar
:where
(.foo, div)
ID
=
0
CLASS
=
1
TAG
=
0
:where
behaves like
:is
without adding any specifi
city.
:where(
S1
,
S2
, ...)
actually not
pseudo-classes
Hack
: repeat to
increase
specifi
city
.foo.foo.foo
#bar#bar#bar
ID
=
0
CLASS
=
3
TAG
=
0
ID
=
3
CLASS
=
0
TAG
=
0
Order of importance
10
Pt1. Language
Specifi
city
<style>
p { color: white; }
p { color: black; }
.foo { color:
blue
!important
; }
</style>
<p>black</p>
<p
style
="color:
red
;">
red
</p>
<p class="foo"
style
="color: red;">
blue
</p>
<p class="foo"
style
="color:
red
!important
;">
red
</p>
!important
rules
CSS in attribute
!important
& inlined
same specifi
city; last rule wins
ID, class, tag
last rule wins
order of comparison
Control priorities with
layers
@layer
base
,
overrides
;
@layer
base
{
/* more specific selectors */
a:link, a:visited { color:
blue
; }
}
@layer
overrides
{
/* less specific, but higher */
a { color:
green
; }
}
a { color:
red
; } /* un-layered rules */
a:visited { color:
revert-layer
; }
low
high
alternative to
!important
and hacks
which rule wins?
topmost
higher
lower
priority list
<a href="/visited-link">
green
</a>
<a href="/not-visited">
red
</a>
revert
to the previous layer
(cascade is
scoped
by layers)
Caveat
:
!important
will reverse the order of layers!
!important
low
!important
high
higher layer
lower layer
order
specifi
city
attribute?
!important
(
Error report | Ask questions
)
@ build-your-own.org
A Visual Guide To CSS
prev ◄─┘
Contents
└─► next