Reputation: 919
I have a question regarding CSS selectors. How do I select a <div>
with a specific class name only when its inside a <ul>
with a class name saft
? This CSS class is used elsewhere and I don't want to change the styling everywhere.
<div id="floater">
<ul class="saft">
<li><div class="textSlide"></li>
</ul>
</div>
Upvotes: 70
Views: 170824
Reputation: 253485
Simply use the CSS descendant selector (a space) between the parent element and the descendant element:
ul.saft div.textSlide {
/* CSS rules */
}
* {
margin: 0;
padding: 0
}
li {
list-style-type: none;
}
ul.saft div.textSlide {
background-color: #f90;
font-weight: #000;
}
<ul class="saft">
<li>
<div class="textSlide">Some text in a textSlide class element</div>
</li>
</ul>
<div class="textSlide">Some more text, also in a textSlide element</div>
In this case the rules applied to the div
of class textSlide
will only apply if its ancestor is a ul
of the class saft
. You could, instead, use the immediate child combinator, the >
but then you'd have to specify the div
in relation to each parent/ancestor up to the one whose class is required, which gives potentially difficult to maintain CSS (not in this case, but it can, over time, become problematic).
Upvotes: 101
Reputation: 7788
you can easily select a div with a specific class name only when its inside a UL with a class name saft like mentioned below css :-
ul.saft .textSlide {
color:red;
}
or see the demo :- http://tinkerbin.com/mcrh7iMq
Upvotes: 0