Sunday, January 21, 2007

CSS: proper paragraph indentation. With elegance.

It is tradition for indentation of paragraphs to apply not to the first paragraph after a heading, but only to the paragraphs following it.

This paragraph, for example, following the first, is indented.

In XHTML all paragraphs are enclosed in p tags. Since they are all p, there is no way to specifically target the first one, or only the ones following, with the standard p CSS selector.
p {text-indent: 1em;} /*would apply to all paragraphs*/
Of course, there are ways to target the first paragraph. Unfortunately, they involve adding to the document markup. Marking the first paragraph with a certain class for example:
<p class="first>this is a first paragraph</p>
p.first {text-indent: 0;}
For sake of Purity and the Separation of Presentation and Markup... No, frankly I don't much care. My motivation for doing this was for a user style sheet, where, of course, I don't have access to the markup. However, I also appreciate the elegance of this trick (mine, and as far as i know, an original):
p + p {text-indent: 1em;}
Using the adjacent sibling operator. Only paragraphs that immediately follow from another is targeted. That means all paragraphs except the first. What's more it even works when paragraphs are interrupted by lists or code sections or an image etc.

Ah, it is just too beautiful...

Hopefully, you will find this useful. And if you do, please do let me know!


Edit: I discovered it was discovered by Chris Curtis as well. Not a surprise. What is in fact surprising is how many people (even w3.org) recommend doing it with the :first-child pseudo-selector:
div > p:first-child { text-indent: 0;}
which is patently hideous.

Well, i guess that makes this an just independent discovery (though more than 2 years later! I
just got into CSS ok?). Now you have to thank Chris as well!

And
blog about it! Two years now and the other methods still dominate search results ???

Labels: , ,

0 Comments:

Post a Comment

<< Home