Reputation: 613
I have a div and inside 100 spans with class s2 and one span with class s1. This s1 span can be anywhere inside the div. I want to apply css to only the first s2 span which is after the s1. How to do it in css ?
<div>
<span class="s2"></span>
<span class="s2"></span>
<span class="s2"></span>
<span class="s2"></span>
<span class="s1"></span>
<span class="s2"></span> <<- i want to style this span
<span class="s2"></span>
<span class="s2"></span>
<span class="s2"></span>
.
.
.
.
.
<span class="s2"></span>
</div>
Upvotes: 2
Views: 1780
Reputation: 65808
There are several ways:
In CSS, you could do:
.s2:nth-child(5) {} /* get any .s2 that is the 5th child within its parent */
.s2:nth-last-child(4) {} /* get any .s2 that is the 4th from last child within its parent */
.s1 + .s2 {} /* get any .s2 that immediately follows an .s1 */
In JavaScript, you could do:
document.querySelector(".s2:nth-child(5)").style.....;
document.querySelector(".s2:nth-last-child(4)").style.....;
document.querySelector(".s1 + .s2").style.....;
These all assume that the hierarchical relationship between all these elements is static.
Learn more about selectors here.
Upvotes: 0
Reputation: 1738
You can use CSS3 operator
.s1 ~ .s2:nth-of-type(1)
http://www.w3schools.com/cssref/sel_gen_sibling.asp
Upvotes: 0
Reputation: 5048
.s1+.s2 {
/* your styles here */
}
The element+element selector is used to select elements that is placed immediately after (not inside) the first specified element.
http://www.w3schools.com/cssref/sel_element_pluss.asp
Upvotes: 3
Reputation: 115212
You can use adjacent sibling selector
This is referred to as an adjacent selector or next-sibling selector. It will select only the specified element that immediately follows the former specified element.
.s1 + .s2 { /* CSS here */ }
.s1 + .s2 {
color: red
}
<div>
<span class="s2">1</span>
<span class="s2">1</span>
<span class="s2">1</span>
<span class="s2">1</span>
<span class="s1">2</span>
<span class="s2">1</span>
<span class="s2">1</span>
<span class="s2">1</span>
<span class="s2">1</span>
<span class="s2">1</span>
</div>
Upvotes: 1