Home > Web Front-end > CSS Tutorial > How to Effectively Target First and Last Children with CSS Pseudo-classes?

How to Effectively Target First and Last Children with CSS Pseudo-classes?

Mary-Kate Olsen
Release: 2024-12-05 07:07:11
Original
324 people have browsed it

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;
}
Copy after login
<div class="container">
  <div class="area">1</div>
  <div class="area">2</div>
  <div class="area">3</div>
  <div class="area">4</div>
</div>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template