That´s my html code:
<a href="#anchor">test</a>
<ul id="anchor"></ul>
Now I want to style my target, which isn´t a problem.
#anchor:target
{
}
But I want to select the sibling of the target (a).
#anchor:target ~ a{
background: blue;
}
It´s not working. How to select the sibling of the target?
Currently, there is no way to style the previous siblings with CSS. To achieve this, you'll have to use javascript.
You can get the next sibling with +
or all <a>
s after your <ul>
with ~
:
#anchor:target + a {
/*
<ul></ul>
<a>will get this one</a>
<a>but not this one</a>
*/
}
#anchor:target ~ a {
/*
<ul></ul>
<a>will get this one</a>
<a>and this one too!</a>
*/
}
In CSS there is no "previous" sibling selector (in CSS2 or CSS3).
The "Selectors Level 4" draft introduces the ! selector, which if I understand it correctly, allows for previous sibling selection.
https://drafts.csswg.org/selectors-4/#subject
However, this is still in draft form, and is far from being supported in all the major browsers.
Sorry, but it's not possible with the current CSS spec.
The only way to really achieve this would be to use JavaScript, or to change the order of your markup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With