Reputation: 169
I have the following code which I would like to select the first child
only of an element that is first child
to appear in blue and the last child that is fourth child
to be in red.
However the grand children are also selected this way, the children of the second child. first grand child appears in blue while the others appear in red.
is there a way I could only select the children without including the grandchildren.
If anything is not clear just comment below and I will reply as soon as possible.
Thanks in advance.
.parent > ul > li > ul
{
display:none;
}
.has_children:hover > ul
{
display:block;
}
.parent > ul :first-child
{
color:blue;
}
.parent > ul :last-child
{
color:red;
}
<div class = "parent">
<ul>
<li>first child</li>
<li class = "has_children">second child
<ul>
<li>first grand child</li>
<li>second grand child</li>
<li>third grand child</li>
</ul>
</li>
<li>third child</li>
<li>fourth child</li>
</ul>
</div>
Upvotes: 0
Views: 158
Reputation: 8695
You can use first-child
and last-child
without select its parent. According to W3:
:first-child pseudo-class
The :first-child pseudo-class matches an element that is the first child element of some other element.
However, you don't need to use grandparent or parent for selecting the first and last child.
li:first-child {
background: red;
}
li:last-child {
background: red;
}
other solution:
li:nth-child(1)
li:nth-of-type(1)
li::nth-last-of-type(1)
Upvotes: 1
Reputation: 122027
Try this
.parent > ul > li:first-child {
color: blue;
}
.parent > ul > li:last-child {
color: red;
}
Upvotes: 1
Reputation: 105863
you could increase your selectors and use first and last-of-type
.parent > ul > li > ul
{
display:none;
}
.has_children:hover > ul
{
display:block;
}
.parent > ul > li:first-of-type
{
color:blue;
}
.parent > ul > li:last-of-type
{
color:red;
}
<div class = "parent">
<ul>
<li>first child</li>
<li class = "has_children">second child
<ul>
<li>first grand child</li>
<li>second grand child</li>
<li>third grand child</li>
</ul>
</li>
<li>third child</li>
<li>fourth child</li>
</ul>
</div>
Upvotes: 1
Reputation: 9959
Try:
.parent > ul > li:first-child
{
color:blue;
}
.parent > ul > li:last-child
{
color:red;
}
This way, you are selecting the first li
and the last li
that comes directly inside the child ul
of the .parent
div.
Upvotes: 2