Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - :target ~

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?

like image 714
Lorenz Avatar asked Oct 18 '22 23:10

Lorenz


2 Answers

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>

    */
}
like image 200
chrona Avatar answered Oct 27 '22 08:10

chrona


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.

like image 22
Sk93 Avatar answered Oct 27 '22 08:10

Sk93