TheDotProduct

Web-tech nerd stuff

Previous sibling, the missing CSS selector?

CSS 2.1 has some really handy selectors, one of which is the adjacent (next) sibling selector which has the form:

el1 + el2
{
color:#f0f;
}

The above would apply a tasty pink(ish) text colour to el2 where it directly follows el1 in HTML element order. Excellent, that can be seriously useful.

The glaring omission (as far as i can see) in the CSS selectors currently available though is the exact opposite selector, previous-sibling which might perhaps have syntax:

el1 - el2
{
color:#f0f;
}

so i would see this as the obvious way to style el2 where it occurs directly before el1 with that same delightful pink(ish) text colour. This would have been immensely helpful in the project I am working on right now as i’m using a flexbox layout on a Zend Framework form and want to swap around the order of the input and label when and only when the input is a checkbox so i’d have loved to have been able to do:

label - input[type="checkbox"]
{
order:-1;
}

on HTML source of:

<div>
<label for="a">
Label text
</label>
<input type="checkbox" name="a" id="a">
</div>

There is also currently a non-direct sibling selector which uses a tilda in place of the plus, the opposite of this could perhaps be:

el1 -~ el2
{
color:#f0f;
}

Please, please, please can we have these browser devs? i’m certainly not the first to ask for them and I am aware that e.g. jQuery implement these so it obviously makes sense.

Created: Thu, 08 Nov 2012 12:00:00 GMT
Last modified: Thu, 08 Nov 2012 12:00:00 GMT