[CSS Selector] E:last-child
Using selector:last-child, you can apply styles to the last child element. This is commonly called a "pseudo-class." It is equivalent to ':nth-last-child(1)'. It does not work in IE7 and earlier.
To target all last child elements, use '*:last-child' or simply ':last-child'. Note that without using '>', writing just ':last-child' applies to the last child among all descendants. For example, 'div :last-child' applies to the last child of every descendant within the div. Text nodes (anonymous blocks) are ignored.
Sample Code
div.hoge :last-child { color: red;} /* Makes the last child among all descendants of the div with class 'hoge' red. */
div.hoge1 > :last-child { color: blue;} /* Makes the last direct child of the div with class 'hoge1' blue. */
Browser Display Result
div.hoge :last-child { color: red;} /* Makes the last child among all descendants of the div with class 'hoge' red. */
div.hoge1 > :last-child { color: blue;} /* Makes the last direct child of the div with class 'hoge1' blue. */
<div class="hoge"> <p>This is the first p element inside the div with class 'hoge'.</p> <div> <p>This is the first p element inside the inner div.</p> <p>This is the last p element inside the inner div.</p> </div> <p>This is the last p element inside the div with class 'hoge'.</p> This is a text node. Text nodes are ignored. </div> <div class="hoge1"> <p>This is the first p element inside the div with class 'hoge1'.</p> <div> <p>This is the first p element inside the inner div.</p> <p>This is the last p element inside the inner div.</p> </div> <p>This is the last p element inside the div with class 'hoge1'.</p> </div>
Note that when combining element name, id, class, or attribute selectors with ':last-child', it first checks if the element is the last child, then checks whether it also matches the specified element name, id, class, or attribute. For example, 'p.hoge:last-child' only applies if the last child is a p element with class 'hoge'. Use ':last-of-type' if you want to filter by element type.
div div.hoge:last-child { color: red;} /* Applies in red only if the last descendant of a div is a div with class 'hoge'. */
<div> <div class="hoge">This is the first div with class 'hoge' inside the outer div.</div> <div> <div>This is the first div inside the inner div.</div> <div>This is the last div inside the inner div.</div> </div> <div class="hoge">This is the last div with class 'hoge' inside the outer div.</div> </div>
Browser Compatibility
2 and earlier ×
8 ×
7 ×
6 ×
8 and earlier ×
1 and earlier ×
Android Browser
4.4+ ○
3 and earlier ×※ Version data is based on MDN.
If you find any errors or copyright issues, please contact us.