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

(singke) #1
ptg16476052

190 LESSON 8: Using CSS to Style a Site


You’ve already seen the basic descendant selector, which looks like this:
p span.important { font-weight: bold }
That selector matches any <span> tag with the class important that’s nested inside a <p>
tag. The child selector is slightly stricter; it looks like this:
p > span.important { font-weight: bold }
That selector only matches if the <span> tag is a child of the <p> tag. It would not match
the <span> tag in the following paragraph, whereas the descendant selector would:
<p>This is a paragraph. <em>This is an
<span class="imprtnt">important</span> sentence.</em></p>

Let’s say that you have some nested lists on a page, and you have a style that should
only apply to items in the top-level list. This is another example in which the descendant
selector would make sense:
ul.topmost > li { color: green; }
The items in the topmost list would be green. The items in the other lists would not.
Finally, there’s the next sibling selector, which uses the + operator. The selector h1 + p
matches the first paragraph that follows a first level heading, assuming they both have the
same parent. You could use this rule if you wanted to add special styling to the lead para-
graphs for stories on your site. The ~ selector matches any siblings, not just the first. So
h1 ~ p would match any paragraph that follows an <h1> tag.

Pseudo-Classes


A couple of pseudo-classes can also be used to apply styles to content based on its posi-
tion on the page. For example, the :first-letter pseudo-class selects only the first
letter in each of the elements selected by the selector. Likewise, the :first-line pseudo-
class selects the first line of text in the element.
Let’s say you want to create what’s known as a drop-cap, a large capital letter at the
beginning of a block of text. You could do it by wrapping the character in a <span> tag,
but using the :first-letter pseudo-class, you can avoid adding an element to the page.
To create the drop-cap, you’ll need to increase the font size, float the character to the left,
and manipulate the padding to be sure that the appearance is correct. Figure 8.20 shows
the re sult.
p:first-letter {
font-size: 300%;
float: left;
font-family: sans-serif;
padding: 0 5 px;
}
Free download pdf