Wandering Thoughts archives


A use for CSS adjacent selectors

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.)

web/CSSAdjacentSelectors written at 22:26:51; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.