Reputation: 35883
Context
I would like to style differently lists with only one item versus lists with multiple items.
Currently I would like to have list-style-type:none;
and different padding-left
for lists which have only one item.
Question
I do know how to write javascript code what achieves this goal by manipulating DOM, but I am asking is it possible somehow using pure CSS?
Upvotes: 2
Views: 1597
Reputation: 1434
You can do this using "only-child" CSS pseudo-class, like below.
li{ color:red}
li:only-child {
color:green;
}
<ul>
<li>1st Item</li>
<li>2nd Item</li>
<li>3rd Item</li>
</ul>
<ul>
<li>Only Item</li>
</ul>
Here when ul has only child element its color will be green. And when ul has multiple child element's there color will be red. You can find more details about it on MDN Docs.
Upvotes: 1
Reputation: 36512
There's a really nice pseudo-class, only-child, in CSS but some older browsers don't support it so if you need to support older versions you can use both first and last child selectors on an element:
li:first-child:last-child {
list-style-type: none;
}
<h2>List with only one entry</h2>
<ul>
<li>Only child</li>
</ul>
<h2>List with more than one entry</h2>
<ul>
<li>first li</li>
<li>second li</li>
</ul>
Upvotes: 1
Reputation: 1568
Yes, CSS has a built-in selector for that which is only-child
.
You can then select child items of parents that only have one child like in the code below.
p:only-child { /*this selects <p> elements of parents that have only one <p> child */
color:red;
}
<div>
<p>I am an only child</p>
</div>
<div>
<p>We are many childs</p>
<p>We are many childs</p>
<p>We are many childs</p>
</div>
Upvotes: 5