'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 1:[1]
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>
Solution 2:[2]
This could work for you:
div {
color: black;
float: right;
}
.active + div {
color: pink;
}
<div class='third'>third</div>
<div class='second active'>second</div>
<div class='first'>first</div>
Solution 3:[3]
CSS doesn't have direct support for this as of now, but jQuery makes it relatively painless, and assuming this is a requirement for your project, could well be the way to go.
In jQuery it would be written something like this:
if element.next().hasClass('active'){
element.addClass('divider')
Solution 4:[4]
Here's a Fiddle
CSS
.divactive {
border-left: 1px solid transparent;
}
jQuery
$(function() {
$('.active').prev('.divider').addClass('divactive');
//or
$('.active').prev('.divider').css({ 'border-left': '1px solid transparent' });
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Mr Br |
Solution 3 | Slater Victoroff |
Solution 4 |