Search code examples
htmlcsscss-selectors

How to apply the style only if next element has specific class?


Markup:

<li class="divider"></li>
<li class="active"><a href="#">Home</a>
<li class="divider"></li>
<li><a href="#">Blog</a></li>

How do I add a style the first .divider only if .active is the next sibling?

I was thinking of .divider + .active but that would apply styles to .active.

.divider {
  border-left: 1px solid #d0d0d0;
}
.active {
  background: #fff;
}
// when the next sibling is .active, border-color: transparent;

Solution

  • You cannot select a previous element in CSS as of now, what you can do is either manually target the class by providing some distinct class to it like

    <li class="divider target_me"></li>
    

    And than simply use

    ul.class_name li.target_me {
       /* Styles goes here */
    }
    

    Else, if it's the first child of li

    You can use ul.class_name li:first-child, if it's not, simply use nth-of-type(n), substitute n with the nth number of your li, this way you don't need to call classes too.

    For example

    ul.class_name li:nth-of-type(2) {
       /* Styles here */
    }
    

    The above selector will select 2nd child of ul element with that specified class name.


    Still not happy with CSS? You can opt for JS/jQuery solution, but if the markup is static, I would suggest you to use nth and if you have access to markup you can atleast call class on the element you want to style..


    Note: You cannot nest li tag as a direct child to li, consider changing your markup to below ..

    <ul>
       <li>
           <a href="#">Home</a>
           <ul>
              <li>Sub</li>
           </ul>
       </li>
    </ul>