2

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>
2

4 Answers 4

3
.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

1

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>

0

You can use CSS3 operator

.s1 ~ .s2:nth-of-type(1)

http://www.w3schools.com/cssref/sel_gen_sibling.asp

2
  • 1
    This also selects all .s2 elements after .s1. The question asked how to select only the next .s2 element.
    – chazsolo
    Commented Feb 3, 2017 at 17:56
  • Try adding :nth-of-type(1) after s2
    – hya
    Commented Feb 3, 2017 at 17:58
0

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.

2
  • And you don't even need to use JavaScript; those are all valid selectors in CSS, which is what the OP asked for.... Commented Feb 3, 2017 at 17:56
  • 1
    True, but the question was tagged with "JavaScript", so I offered an answer that would cover both. Commented Feb 3, 2017 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.