span click <p>
color change
span:focus~.to-be-changed {
color: red;
}
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
<span tabindex="0">Click me!</span>
Click me!
span click <p>
color change
span:focus~.to-be-changed {
color: red;
}
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
<span tabindex="0">Click me!</span>
Click me!
The ~
refers to all the siblings after the element. In your example the .to-be-changed
is a previous sibling. You can place them in the order you need in the dom and then reorder them using flex
and order
span:focus~.to-be-changed {
color: red;
}
.container{
display: flex;
flex-direction: column;
}
.container .to-be-changed{
order: 1;
}
.container span{
order: 2;
}
<div class="container">
<span tabindex="0">Click me!</span>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
</div>
.parent {display: flex;}
span { order: 2;}
.to-be-changed {order: 1;}
span:active~.to-be-changed {
color: red;
}
<div class="parent">
<span tabindex="0">Click me!</span>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
</div>
So far (Feb.2019) you cannot select parent of an element, or the previous sibling of an element.
But you can do a css trick to place the <p>
element after <span>
element in html but display the <p>
element before span
element. Then you can achieve the goal. The snippet above is an example, if you need to support old browser you can also use float:right;
instead.
However, in the future, we will have ':has()' css selector which will allow us to select parent of an element. Here you can check this selector info :has() selector.