0brine
0brine

Reputation: 486

CSS select element which has a following element

I was trying to select The first element of 2 Folloing elements, and I am not allowed to change the HTML :(

For Exampe:


span + span {
 border: red solid 1px;
}
<span>I wanna select this</span>
<span>not this</span>
<br>
<span>not this</span>
<br>
<span>I wanna select this</span>
<span>not this</span>

I know I can get the second span like this "span + span"
but is there a way to get the first Element?

Upvotes: 2

Views: 1411

Answers (3)

Ritika Gupta
Ritika Gupta

Reputation: 376

Please Check if this serves your purpose.

span:first-of-type{
border: 1px solid red;
}
.line-break + span:nth-of-type(2n){
border: 1px solid red;
}
<span>I wanna select this</span>
<span>not this</span>
<br class="line-break">
<span>not this</span>
<br class="line-break">
<span>I wanna select this</span>
<span>not this</span>

Upvotes: 1

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13536

If there are two elements in the container, then the 1st of them is the first child and the second last child of its parent. Thus, to select only first children of such containers, you can use the following selector:

span:first-child:nth-last-child(2) { ... }

Upvotes: 1

Mohammad Fared
Mohammad Fared

Reputation: 658

wrap it with parent and use selector like that

.example span:first-child{}

Upvotes: 0

Related Questions