Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 614
Jürgen Paul Avatar asked Sep 07 '13 19:09

Jürgen Paul


People also ask

How do you apply a style to several specific element types in CSS?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

How do you select an element with a specific class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How do you target the next element in CSS?

The element+element selector is used to select an element that is directly after another specific element.

How do I apply CSS to child element based on parent?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinator ( > ), which is placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.


1 Answers

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>
like image 168
Mr. Alien Avatar answered Sep 21 '22 14:09

Mr. Alien