Home >Web Front-end >CSS Tutorial >How to Effectively Target First and Last Children with CSS Pseudo-classes?
How to Target First and Last Children in CSS
Selecting the first and last child elements using CSS can be tricky, as the "first-child" and "last-child" pseudo-classes apply to the immediate children of a parent element.
In the provided CSS code, targeting the first and last child elements of the ".area" class is not working because the elements are not direct children of a container element. To make the selection work, you can add a container element and specify its children as the target.
Here's an example that includes a container element:
.container { display: flex; } .area { height: 100px; width: 100px; } .container > .area:first-child { background-color: red; } .container > .area:last-child { background-color: green; }
<div class="container"> <div class="area">1</div> <div class="area">2</div> <div class="area">3</div> <div class="area">4</div> </div>
With this modification, the ".area" elements become direct children of the ".container" element, and the "first-child" and "last-child" pseudo-classes can be used to select the first and last child elements accordingly.
The above is the detailed content of How to Effectively Target First and Last Children with CSS Pseudo-classes?. For more information, please follow other related articles on the PHP Chinese website!