The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Pseudo-classes and Pseudo-elements 45

Finally, some HTML5 elements can have a permitted range of values,
set by using the min and max attributes. You can style these elements depend-
ing on whether the current value is in or out of range by using, once again,
a pair of namesake pseudo-classes:

:in-range {...}
:out-of-range {...}

Pseudo-elements


Like pseudo-classes, pseudo-elements provide information that is not speci-
fied in the document tree. But where pseudo-classes use “phantom” condi-
tions such as an element’s position in the tree or its state, pseudo-elements
go further and allow you to apply styles to elements that don’t exist in the
tree at all.
In CSS2, the four pseudo-elements are :first-line and :first-letter,
which select subelements in text nodes, and :after and :before, which allow
you to apply styles at the beginning and end of existing elements. CSS3
doesn’t introduce any new pseudo-elements, but it refines the definitions
slightly and introduces a new syntax to differentiate them from pseudo-
classes. In CSS3, pseudo-elements are prefixed with a double colon (::),
like so:

::first-line {...}
::first-letter {...}
::after {...}
::before {...}

noTe The single colon syntax is still accepted for reasons of backward compatibility,
although it is deprecated and you shouldn’t use it going forward.

The ::selection Pseudo-element


Early versions of the CSS3 Selectors module included the definition of a
::selection pseudo-element. Although formally removed from the module,
it has been well implemented across desktop browsers (less so in mobile
browsers). ::selection is used to apply rules to an element that the user has
selected in the browser (for example, a portion of a text node):

::selection {...}

Only a limited number of properties can be applied with :: selection:
color, background-color, and the background shorthand (although not
background-image). Using ::selection, you can do something like this:

p::selection {
background-color: black;
color: white;
}
Free download pdf