Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

192 LESSON 8: Using CSS to Style a Site


The :hover and :focus pseudo-classes are applied based on how the user is interact-
ing with the page. The :focus selector is triggered when a matching element has focus.
Focus is mostly associated with HTML forms, so I’ll come back to it in Lesson 12,
“Designing Forms.” Selectors that include the :hover pseudo-class are activated when
the user has his pointer over the matching element. You’ve already see how the :hover
pseudo-class can be used with links—it can in fact be used with any element on a page.
To change the background color and border when users move their pointer over a para-
graph, you’d use the following style sheet rule:
p:hover {
background-color: yellow;
border: 1px solid green;
}

Over time, CSS has evolved to enable you to make your pages more dynamic only
through the use of style sheets. At one time, if you wanted to change styles on your page
after it loaded, you had to write a script using JavaScript, which I’ll discuss later in the
book. Now, a number of CSS selectors enable you to add dynamic content to your pages
without scripting.
You can even use CSS to modify the contents of the page directly using the :before and
:after selectors. The newer notation is ::before and ::after, but :before and :after
are more widely supported. These selectors create a pseudo-element that’s the first child
of the matched element. You can use a style property called content to insert any content
you like into that pseudo-element, and it will be displayed on the screen. Using :before,
:after, and content, you can make changes to the actual content of your page.
Let’s say I have a style guide for my site that requires me to place square brackets around
any abbreviation I use. I have the following content for my page:
<p><abbr>NASA</abbr> is responsible for the US space program.</p>
Rather than editing the page to add the square brackets, which are a stylistic element
more than proper content, I can add them using CSS. Here’s the style sheet:
abbr:before { content: "[" }
abbr:after { content: "]" }

You can see the results in Figure 8.22.
Free download pdf