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.
| This entry was posted by Neil Craig on November 6, 2012 at 7:09 pm, and is filed under CSS, CSS3, General Web-Development. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

about 6 months ago
In your example with the checkbox, you could actually just use the normal + selector. The checkbox is after the label in the markup, so it’s not really a problem.
Also, CSS Selectors Level 4 introduces a new syntax for choosing the subject of your selectors (http://dev.w3.org/csswg/selectors4/#subject)
This basically means you can write something like !el1 + el2 {}
to target el1
about 6 months ago
Hi Stian
.
Thanks for your reply. Yes, you’re right – that wasn’t a great example.
It’s good to see the level4 selector proposal, i hadn’t seen that yet. Element targetting was actually going to be the subject of my next post, i think that is going to be immensely useful – hopefully it won’t be too long before it’s usable in the wild
EDIT: Sorry, just re-read. I don’t see how with + we could style the preceeding label element.
Cheers
Neil