Is there a better way to write this:
#container ul ul ul
I need to target the third nested list and every other one after that?
Is there a better way to write this:
#container ul ul ul
I need to target the third nested list and every other one after that?
You can do it in several ways. If you simply want to assign a css property from the third ul element upwards (i.e.: 3 ul, 4 ul , n ul) the easiest way would be to use an asterisk *
.
#container ul ul > * {
font-style: italic
}
I have used several selectors in the following example. Which one you actually use is up to you.
#container ul ul ul {
color: green;
}
div ul > ul > ul {
font-size: 30px;
}
.third {
text-decoration: underline;
}
#container ul ul > * {
font-style: italic;
font-weight: bold;
}
blockquote {
color: gray;
}
<blockquote>I need to target the third nested list and every other one after that?
</blockquote>
<div id="container">
<ul>
<li>1 ul</li>
<ul>
<li>2 ul</li>
<ul class="third">
<li>3 ul</li>
<ul class="third">
<li>4 ul</li>
<ul>5 ul</ul>
</ul>
</ul>
</ul>
</ul>
</div>
Maybe use the >
selector in css or assign the element a className
, but I don't think there is an easier way to do that rather than these two ways.
By using >
, you will directly specify the child element (e.g. A) of the parent element (e.g.B) and won't select the appended child element of A.
Check more here: What is the difference between '>' and a space in CSS selectors?
You are trying to get the nested ul
, so things like nth-of-child
or nth-of-type
will not work for you.
#ul>ul>ul {
background: red
}
<ul id='ul'>
<ul>
<ul>
Yes
</ul>
</ul>
</ul>
Confused with difference between space and >
in css?
Check this as example:
#ul>ul>ul {
background: red
}
<ul id='ul'>
<ul>
<ul>
This will be considered
</ul>
<div>
<ul>This will not be considered</ul>
</div>
</ul>
</ul>
#ul ul ul {
background: red
}
<ul id='ul'>
<ul>
<ul>
This will be considered
</ul>
<div>
<ul>This will be considered as well</ul>
</div>
</ul>
</ul>
the other answers seem to have ignored your other criterion, which was: 'and every other one after that'
this answers that question
#content ul ul ul:first-of-type,
#content ul ul ul ~ ul:nth-of-type(odd) { color: green;}
<div id="content">
<ul>
<li>one</li>
<ul>
<li>two</li>
<ul>
<li>three.1</li>
</ul>
<ul>
<li>three.2</li>
</ul>
<ul>
<li>three.3</li>
</ul>
<ul>
<li>three.4</li>
</ul>
<ul>
<li>three.5</li>
</ul>
</ul>
</ul>
</div>
yeap it's messy-looking css (not really, IMHO, but to each their own) but if you don't have access to add classes to the markup, this is the way.