Css :last-child pseudo class apply to an element if it is last sibling in all direct child elements of its parent. It can be used to apply different style (e.g. botton border) on last child. Here are some examples.
:last-child positive example
<style type="text/css" media="screen"> .foo > p:last-child { background-color: lightgreen; } </style> <div class="foo"> <p>p1</p> <p>p2</p> <p>p3</p> </div>
Few points to note:
- Here the :last-child pseudo class style applies to all
p
direct child elements of div of class foo. - To apply style to all direct child and descendant p elements we could have used
.foo p:last-child
. See more info at CSS direct child vs any descendant selector.
:last-child negative example
Here no p element is last child. So background color won’t be set.
<style type="text/css" media="screen"> .foo > p:last-child { background-color: lightgreen; } </style> <div class="foo"> <p>p1</p> <p>p2</p> <p>p3</p> <div>div1</div> </div>
:last-child – include nested child elements example
This example contains two p elements which fulfil last-child requirements.
<style type="text/css" media="screen"> .foo p:last-child { background-color: lightgreen; </style> <div class="foo"> <p>p1</p> <p>p2</p> <div><p>in_div_p1</p><p>in_div_p2</p></div> <p>p3</p> </div>
:last-child – exclude nested child elements example
This example contains two p elements which fulfil last-child requirements. But since we are using .foo > p
, only direct p child elements are eligible for this style.
<style type="text/css" media="screen"> .foo > p:last-child { background-color: lightgreen; } </style> <div class="foo"> <p>p1</p> <p>p2</p> <div><p>in_div_p1</p><p>in_div_p2</p></div> <p>p3</p> </div>