Menu
CoddyTech

选择最后一个子元素

本课属于 Coddy HTML 学习旅程的“精通 CSS”单元。第 14 课,共 43 课。

:last-child 伪类会选择作为其父元素最后一个子元素的元素。

例如:

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

若只为最后一个段落设置样式,请使用 :last-child 伪类:

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

应用这些 CSS 后,只有“最后一个段落”会变成红色并加粗,因为它是父级 div 的最后一个子元素。

challenge icon

挑战

简单

创建一条 CSS 规则,为任意一组段落中的最后一个 <p> 元素设置样式。

  1. 将它的背景色设为蓝色(#046ae0),文本设为白色。
  2. 将最后一个段落的字重设为粗体。

亲手试试

<!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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

精通 CSS中的所有课

自己练习: Web 在线编辑器