Working with Pseudo-Classes
Many HTML elements have special states or uses associated with them that can be styled independently. One prime example of this is the link tag, <a>, which has link (its normal state), a visited state (when the visitor has already been to the page represented by the link), hover (when the visitor has the mouse over the link), and active (when the visitor clicks the link). All four of these states can be styled separately.
A pseudo-class is a predefined state or use of an element that can be styled independently of the default state of the element .
- Links (Table 4.3)—Pseudo-classes are used to style not only the initial appearance of the anchor tag, but also how it appears after it has been visited, while the visitor hovers the mouse over it, and when visitors are clicking it.
Table 4.3. Link and Dynamic Pseudo-Classes
Format
Selector Name
Elements Are Styled If...
:link
Link
the value of href is not in history
:visited
Visited link
the value of href is in history
:target
Targeted link
a targeted anchor link
:active
Active
the element is clicked
:hover
Hover
the pointer is over the element
:focus
Focus
the element has screen focus
- Dynamic (Table 4.3)—Pseudo-classes can be applied to any element to define how it is styled when the user hovers over it, clicks it, or selects it.
- Structural (Table 4.4)—Pseudo-classes are similar to the sibling combinatory selectors but allow you to specifically style elements based on an exact or computed numeric position.
Table 4.4. Structural/Other Pseudo-Classes
Format
Selector Name
Elements Are Styled If...
:root
Root
is the top level element in a document
9
:empty
Empty
has no children
9
:only-child
Only child
has no siblings
9
:only-of-type
Only of type
has its unique selector among its siblings
9
:first-child
First-child
is the first child of another element
9
:nth-of-type(n)
Nth of type
is the nth element with that selector
9
:nth-last-of-type(n)
Nth from last of type
is the nth element with that selector from the last element with that selector
9
:last-child
Last child
is the last child in the parent element
9
:first-of-type
First of type
is the first of its selector type in the parent element
9
:last-of-type
Last of type
is the last of its selector type in the parent element
9
:lang()
Language
has a specified language code defined
8
:not(s)
Negation
is not using specific selectors
9
- Other (Table 4.4)—Pseudo-classes are available to style elements based on language or based on what tag they are not.
Styling links
Although a link is a tag, its individual states are not. To set properties for these states, you must use the pseudo-classes associated with each state that a link can have (in this order):
- :link lets you declare the appearance of hypertext links that have not yet been selected.
- :visited lets you set the appearance of links that the visitor selected previously—that is, the URL of the href attribute in the tag that is part of the browser’s history.
- :hover lets you set the appearance of the element when the visitor’s pointer is over it.
- :active sets the style of the element when it is clicked or selected by the visitor.
For ideas on which styles to use with links, see the sidebar “Picking Link Styles.”
To set contrasting link appearances
- Style the anchor tag.
a {...}
Although not required, it’s best to first define the general anchor style (Code 4.6). This differs from setting the :link pseudo-class in that these styles are applied to all the link pseudo-classes. So, you want to declare any styles that will remain constant or are changed in only one of the states.
Code 4.6. The link styles are set for the default and then all four link states, creating color differentiation . Notice also that I’ve turned off underlining with text decoration but added an underline effect using border bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Alice’s Adventures in Wonderland</title> <style type="text/css" media="all"> a { text-decoration: none; font-size: 2em; } a:link { color: darkred; border-bottom: 1px solid red; } a:visited { color: darkred; border-bottom: 1px dashed red; } a:hover { color: red; border-bottom: 1px solid pink; } a:active { color: pink; border-bottom: 1px solid pink; } </style> </head> <body> <nav> <h2>TOC:</h2> <ol> <li><a href="AAIWL-ch01.html">Down the Rabbit-hole</a></li> <li><a href="AAIWL-ch02.html">The Pool of Tears</a></li> <li><a href="AAIWL-ch03.html">A Caucus-race and a Long Tale</a></li> <li><a href="AAIWL-ch04.html">The Rabbit sends in a Little Bill</a></li> <li><a href="AAIWL-ch05.html">Advice from a Caterpillar</a></li> <li><a href="AAIWL-ch06.html">Pig and Pepper</a></li> <li><a href="AAIWL-ch07.html">A Mad Tea-party</a></li> <li><a href="AAIWL-ch08.html">The Queen's Croquet-ground</a></li> <li><a href="AAIWL-ch09.html">The Mock Turtle's Story</a></li> <li><a href="AAIWL-ch010.html">The Lobster Quadrille</a></li> <li><a href="AAIWL-ch011.html">Who Stole the Tarts?</a></li> <li><a href="AAIWL-ch012.html">Alice’s Evidence</a></li> </ol> </nav> </body> </html>
- Style the default link state. Type the selector (anchor tag, class, or ID) of the element you want to style, followed by a colon (:), and then link.
a:link {...}
You can override styles set for the anchor tag, but this rule should always come before the :visited pseudo-class.
- Style the visited link style. Type the selector (anchor, class, or ID) of the element you want to style, followed by a colon (:), and then visited.
a:visited {...}
- Style the hover link state. Type the selector (anchor, class, or ID) of the element you want to style, followed by a colon (:), and then hover.
a:hover {...}
- Style the active link state. Type the selector (anchor, class, or ID) of the element you want to style, followed by a colon (:), and then active.
a:active {...}
- Style is applied to the link state as needed.
<a href="AAIWL-ch01.html">...</a>
All links on the page will obey the rules you lay down here when styling the various link states. You can—and should—use selective styling to differentiate link types.
In this example, the pseudo-classes are applied directly to the anchor tag, but any class or ID could have been used as long as it was then applied to an anchor tag.
Styling for interaction
Once loaded, Web pages are far from static. Users will start interacting with the page right away, moving their pointers across the screen and clicking hither and yon. The dynamic pseudo-classes allow you to style elements as the user interacts with them, providing visual feedback:
- :hover—Same as for links, but sets the appearance of the element when the pointer is hovering over it.
- :focus—Applied to elements that can receive focus, such as form text fields.
- :active—Same as for links, but sets the style of the element when it is clicked or selected.
To define a dynamic pseudo-class
- Style the default element.
input {...}
Although optional, it’s generally a good idea to set the default, non-dynamic style for the elements receiving dynamic styles (Code 4.7).
- Style the hover state of the element. Type the selector (HTML, class, or ID), a colon (:), and then hover.
input:hover {...}
As soon as the pointer enters the element’s box (see Chapter 10 for details about the box model), the style change will occur.
The results of Code 4.7. This shows a simple form field in the four dynamic states. Providing this visual feedback can help users know which form field is ready for use or that they have clicked a button.
Code 4.7. The input elements, with a special style for the button type, are set to change style when the user interacts with them by hovering, selecting (focus), or clicking (active) .
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Alice’s Adventures in Wonderland</title> <style type="text/css" media="all"> input { border: 3px solid gray; background-color: silver; color: gray; padding: 0 5px; font-size: 1.5em; } input[type="button"] { border-radius: 1em; color: silver; background-color: gray; } input:hover { background-color: white; border-color: pink; color: silver; } input:focus { border-color: red; background-color: white; color: black; outline: none; } input:active { color: red; border-color: pink; background-color: silver; } </style> </head> <body> <footer> <label>Mailing List:</label> <input type="text" value="email" placeholder="enter your eMail"> <input type="button" class="active" value="submit"> </footer> </body> </html>
- Style the focus state of the element. Type the selector (HTML, class, or ID), a colon (:), and then focus.
input:focus {...}
As soon as the element receives focus (is clicked or tabbed to), the style change occurs and then reverts to the hover or default style when the element loses focus (called blur).
- Style the active state of the element. Type the selector (HTML, class, or ID), a colon (:), and then active.
input:active {...}
As soon as the user clicks within the element’s box (explained in Chapter 10), the style change will occur and then revert to either the hover or default style when released.
- The styles are applied to the elements’ states as necessary in reaction to the user.
<input type="button" value="Submit">
All the tags using the specific selector will have their states styled.
Styling specific children with pseudo-classes
Designers often want to apply a style to an element that is the first element to appear within another element, such as a parent’s first child.
The first-child pseudo-element has been available since CSS2; however, CSS3 offers an assortment of new structural pseudo-elements for styling an element’s child element exactly (Table 4.4):
- :first-child—Sets the appearance of the first instance of a selector type if it is the first child of its parent.
- :first-of-type—Sets the appearance of an element the first time its selector type appears within the parent.
- :nth-child(#)—Sets the appearance of the specific occurrence of the specified child element. For example, the third child element of a paragraph would be p:nth-child(3).
- :nth-of-type(#)—Sets the appearance of the specific occurrence of a selector type within the parent. For example, the seventh paragraph would be p:nth-of-type(7).
- :nth-last-of-type(#)—Sets the appearance of the specific occurrence of a selector type within the parent, but from the bottom. For example, the third paragraph from the bottom would be p:nth-last-of-type(3).
- :last-child—Sets the appearance of the element of the indicated selector type if it is the last child of the parent.
- :last-of-type—Sets the appearance of the last instance of a particular selector type within its parent.
To style the children of an element
- Style the children based on their positions in the parent. Type the selector (HTML, class, or ID) of the element you want to style, a colon (:), and one of the structural pseudo-elements from Table 4.4 (Code 4.8).
li:first-child {...} li:first-of-type {...} li:nth-of-type(3) {...} li:nth-last-of-type(2) {...} li:last-child {...} li:last-of-type {...}
- Elements will be styled if they match the pattern.
<li>...</li>
Set up your HTML with the selectors from Step 1 in mind.
Code 4.8. The list has styles set based on the location within the list .
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Alice’s Adventures in Wonderland</title> <style type="text/css" media="all"> li { font-size: 1.5em; margin: .25em; } li:first-child { color: red; } li:first-of-type { border-bottom: 1px solid orange; } li:nth-child(2) { color: yellow; } li:nth-of-type(6) { color: green; } li:nth-last-of-type(2) { color: blue; } li:last-of-type { border-bottom: 1px solid indigo; } li:last-child { color: violet; } </style> </head> <body> <nav> <ol> <li>Down the Rabbit-hole</li> <li>The Pool of Tears</li> <li>A Caucus-race and a Long Tale</li> <li>The Rabbit sends in a Little Bill</li> <li>Advice from a Caterpillar</li> <li>Pig and Pepper</li> <li>The Queen's Croquet-ground</li> <li>The Mock Turtle's Story</li> <li>The Lobster Quadrille</li> <li>Who Stole the Tarts?</li> <li>Alice’s Evidence</li> </ol> </nav> </body> </html>
Styling for a particular language
The World Wide Web is just that—all around the world—which means that anyone, anywhere can see your pages. It also means that Web pages are created in many languages.
The :lang() pseudo-class lets you specify styles that depend on the language specified by the language property.
To set a style for a specific language
- Style an element based on its language code. Type the selector (HTML, class, or ID) of the element you want to style, a colon (:), lang, and enter the letter code for the language you are defining within parentheses (Code 4.9).
p:lang(fr) {...}
- The element is styled if it has a matching language code. Set up your tag in the HTML with the language attributes as necessary.
<p lang="fr">...</p>
If the indicated selector has its language attribute equal to the same value that you indicated in parentheses in Step 1, the style is applied.
You can use any string as the language letter code, as long as it matches the value in the HTML. However, the W3C recommends using the codes from RFC 3066 or its successor. For more on language tags, visit www.w3.org/International/articles/language-tags.
Code 4.9. Styles are set to turn paragraphs red if they are in French (fr) .
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Alice’s Adventures in Wonderland</title> <style type="text/css" media="all"> q:lang(fr) { quotes: '«''»'; color: red; } </style> </head> <body> <article class="chaptertext"> <p>Alice was beginning to get very tired of sitting by her sister on the bank, and of having → nothing to do: once or twice she had peeped into the book her sister was reading, but it had no → pictures or conversations in it, <q>and what is the use of a book,</q> thought Alice, <q>without → pictures or conversations?</q></p> <p class="translation" lang="fr">Alice commençait à être très fatigué d'être assis par sa sœur sur → la rive, et de n'avoir rien à faire: une fois ou deux, elle avait regarda dans le livre de sa sœur → lisait, mais il n'avait pas d'images ni dialogues en elle, <q>et ce qui est l'utilisation d'un → livre,</q> pensait Alice, <q>sans images ni dialogues?</q></p> </article> </body> </html>
The results of Code 4.9 show the paragraph in French rendered in red (with my apologies to French speakers).
Not styling an element
So far you’ve looked at ways to style a tag if it is something. The negation selector, :not, allows you to not style something for a particular selector.
To not set a style for a particular element
- Style elements to exclude certain selectors. Type the selector (HTML, class, or ID) of the element you want to style, a colon (:), not, and enter the selectors you want excluded from this rule in parentheses (Code 4.10).
p:not(.dialog) {...}
- The element is not styled if it contains the indicated selector.
<p class='dialog'>...</p> <p>...</p>
The styles are applied to elements that match the initial selector but not the selector in parentheses.
Code 4.10. When the element is a paragraph that does not use the dialog class, it will be displayed in red and italics .
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Alice’s Adventures in Wonderland</title> <style type="text/css" media="all"> q:lang(fr) { quotes: '«''»'; } p:not(.translation) { color: red; } </style> </head> <body> <article class="chaptertext"> <p>Alice was beginning to get very tired of sitting by her sister on the bank, and of → having nothing to do: once or twice she had peeped into the book her sister was reading, → but it had no pictures or conversations in it, <q>and what is the use of a book,</q> → thought Alice, <q>without pictures or conversations?</q></p> <p class="translation" lang="fr">Alice commençait à être très fatigué d'être assis par sa sœur → sur la rive, et de n'avoir rien à faire: une fois ou deux, elle avait regarda dans le livre de sa → sœur lisait, mais il n'avait pas d'images ni dialogues en elle, <q>et ce qui est l'utilisation d'un → livre,</q> pensait Alice, <q>sans images ni dialogues?</q></p> </article> </body> </html>