Pages

Tuesday, January 25, 2011

Adjacent Sibling Selectors are a way of styling an element that appears directly adjacent to another element. So, for example, if you knew that the first paragraph to follow an image in your XHTML was always going to be a caption, and you wanted that styled differently, you could write something like this:

img + p {
color: #999;
font-style: italic;
}

This would turn the paragraph immediately following the image gray and italicize it, all without any extra code in your XHTML.

Pseudo-Element Selectors refer to parts of your XHTML that aren’t technically elements of their own right, but can be easily distinguished from the surrounding code due to their nature. The most common two pseudo-elements (and the two we’re using here) are :first-letter and :first-line.

Creating a Book-Style Introductory Line

So what we need to do to create our book-style line is create a drop-cap of the first letter, and the rest of the first line in small caps. And we want to do it without having to resort to classes or IDs to get it done. What we’re assuming in this exercise is that your XHTML is already well-formed – your articles or chapters always start with a heading tag (I’m using < h4 > tags), and you’re using paragraph tags instead of (shudder) line breaks. So here’s how we do it:

You’ll start with some fairly simple XHTML that looks something like this:


Article Titles for Fun and Profit


This is our first paragraph. Don’t you think
the first line should stand out?

Our second paragraph doesn’t need such
fancy-pants styling.

And then we’ll use CSS to style the first line of the first paragraph following our 4th level heading:

h4 + p:first-line {
font-variant: small-caps;
font-size: 1.1em;
}

This gives us a small-capped line that is slightly larger than the rest of the surrounding text. Now, all we need to do is create our drop cap:

h4 + p:first-letter {
float: left;
font-size: 2.5em;
font-weight: bold;
font-family: "Monotype Corsiva",
"Apple Chancery", fantasy;
margin: 5px 5px 5px 0;
}

Here, I’ve floated the letter to the left (which causes the rest of the text to flow around it), increased its size, made it boldface, set it in a scripty font (you could chose any font here, but I was going for a bookish look), and added a bit of a margin to make sure there isn’t any overlap.

We’ve managed to create an introductory line without a single byte of XHTML.

And that’s all there is to it! You can see a finished example here. We’ve managed to create an old-school book-style introductory line without adding a single byte of XHTML. This is a quick and easy way to add some visual appeal to your articles. It could even make for an interesting addition to a print style sheet, adding a bit of classic authenticity.

Now, I have one caveat: this does not work in IE6. But the text simply degrades nicely into an otherwise unaffected first line. No harm, no foul.

No comments:

Post a Comment