A use for CSS adjacent selectors

June 17, 2007

CSS has a very complicated system of CSS selectors, which let you pick out just what you are applying some (cascading) style to; they range from obvious to what I consider obscure, such as adjacent sibling selectors.

(An adjacent sibling selector is written E + F; it matches any F element that is immediately preceded by an E element.)

It turns out that there is a straightforward use for them: interior margins.

Suppose that you have a table where you want the cells in a horizontal row to be separated from each other by some white space (because it looks better and sets them off from each other), but you don't want the overall table to be indented relative to either the left or the right margin.

The simple approach is to give table cells a left or a right padding. However this pushes the overall table around, because the padding of the leftmost or rightmost cell forces the table to have an overall padding. What you really want is to give each cell a left padding except the first cell in a row; in other words, an interior margin.

And this is just right for an adjacent selector:

td + td { padding-left: 1em; }

Every td that is preceded by a td is exactly 'all table cells except the first cell in each row'.

(Possibly this was immediately obvious to everyone except me, but I felt quite happy when I worked it out in the process of adding horizontal tables way back when.)

Written on 17 June 2007.
« Weekly spam summary on June 16th, 2007
What are slot wrapper objects? »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Sun Jun 17 22:26:51 2007
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.