Discover how to style the first and last items perfectly without extra work or mistakes!
Why First-child and last-child in CSS? - Purpose & Use Cases
Imagine you have a list of tasks on a webpage. You want the first task to have a special color and the last task to have a different style.
If you try to style the first and last tasks manually by adding special classes or inline styles, it takes extra work and can break if you add or remove tasks later.
The :first-child and :last-child selectors let you automatically style the first and last items without extra classes, even if the list changes.
<li class="first">Task 1</li> <li>Task 2</li> <li class="last">Task 3</li>
li:first-child { color: blue; }
li:last-child { color: green; }You can style elements based on their position in a list or container, making your design flexible and easy to maintain.
On a navigation menu, highlight the first link as the 'Home' button and the last link as 'Contact' automatically, even if you add more links later.
First-child targets the first element inside a parent.
Last-child targets the last element inside a parent.
They help keep styles consistent without extra HTML changes.