Reputation: 16132
Let's say I have several <p>
elements inside a <div>
like this:
<div>
<p></p>
<p></p>
<p></p> <!-- I want to select the "last" element, <p> or not <p> -->
</div>
Now, say I want to style the last element, <p>
or not <p>
. One way to do that is to use the last-child
selector on the <p>
's like this:
<style>
p:last-child {
/* Awesome styles go here */
}
</style>
How do I style the last element (
<p>
or not<p>
) by referencing<div>
but NOT<p>
?
p:last-child {
color: red;
font-weight: bold
}
<div>
<p>Foo</p>
<p>Bar</p>
<p>Baz</p> <!-- I want to select the "last" element, <p> or not <p> -->
</div>
Upvotes: 2
Views: 81
Reputation: 34244
You can use >
in your selector to describe direct children:
div > p:last-child {
}
This CSS will affect only the p
tags which are the last child of div
tag.
If, for some reason, you don't want to reference p
at all, you can use *
selector:
div > *:last-child {
}
It will affect the last child of the div
whatever it is.
For example:
div > *:last-child {
font-weight: bold;
color: red;
}
<div>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
<div>
<a href="#">1</a>
<a href="#">2</a>
<a href="#">3</a>
</div>
<div>
<span>1</span>
<i>2</i>
<i>3</i>
</div>
Upvotes: 4