Menu
CoddyTech

Chọn phần tử con cuối cùng

Thuộc phần Thành thạo CSS trong hành trình HTML của Coddy. Bài học 14 trên 43.

Lớp giả :last-child chọn các phần tử là phần tử con cuối cùng của phần tử cha.

Ví dụ:

<div class="parent">
  <p>First paragraph</p>
  <p>Middle paragraph</p>
  <p>Last paragraph</p>
</div>

Để định kiểu chỉ cho đoạn văn cuối cùng, hãy dùng lớp giả :last-child:

p:last-child {
  color: red;
  font-weight: bold;
}

Sau khi áp dụng CSS này, chỉ có "Last paragraph" chuyển thành màu đỏ và in đậm vì đây là phần tử con cuối cùng của div cha.

challenge icon

Thử thách

Dễ

Tạo một quy tắc CSS để định dạng phần tử <p> cuối cùng trong bất kỳ nhóm đoạn văn nào.

  1. Đặt màu nền thành màu xanh dương (#046ae0) và màu chữ là trắng .
  2. Đặt độ đậm phông chữ của đoạn văn cuối cùng thành đậm.

Tự làm thử

<!DOCTYPE html>
<html>
<head>
    <title>Targeting the Last Child</title>
  <style>
    /* Write your CSS rule here */

  </style>
</head>
<body>
    <div> 
        <h2>Exploring the Universe</h2>
        <p>The universe is vast, with countless stars and galaxies waiting to be discovered.</p>
        <p>New technologies allow us to explore deeper into space, revealing its many secrets.</p>
        <p>We continue to learn more about distant planets and the possibility of life beyond Earth.</p> 
    </div>
    <div>
        <h2>The Deep Ocean</h2>
        <p>Our oceans are mysterious, covering most of Earth, yet we know so little about them.</p>
        <p>Many species live in extreme conditions, some of which are still being discovered today.</p>
        <p>Exploring the ocean depths gives us insights into life at the planet's most remote locations.</p> 
    </div>
</body>
</html>
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Thành thạo CSS

Tự luyện tập: Playground Web