CSS - 偽類 :last-child



CSS 偽類選擇器:last-child表示包含元素內的最後一個元素。

偽類:last-child類似於:last-of-type,但前者更具體,它針對父元素的最後一個子元素,而後者匹配指定元素的最後一個出現。

語法

:last-child {
    /* ... */
}

CSS :last-child 示例

以下示例演示了:last-child偽類的用法。在這個示例中,CSS 規則僅適用於在<div>元素內找到的最後一個<p>元素,而不會影響同一容器內的其他<p>元素。

<html>
<head>
<style>
   p:last-child {
      color: black;
      background: yellow;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
   }
</style>
</head>
<body>
   <div>Parent element
      <p>first child, so no change</p>
      <p>second/last child, so :last-child pseudo-class applied</p>
   </div>
   <div>Parent element
      <h2>h3 tag, so no change</h2>
      <p><p> tag, is the last child.</p>
   </div>
</body>
</html>

以下示例演示了:last-child偽類的用法,應用於<ul>父元素下的<li>標籤。在這個示例中,CSS 規則僅適用於在<ul>元素內找到的最後一個<li>元素,而不會影響同一容器內的其他<li>元素。

<html>
<head>
<style>
   ul li:last-child {
      color: black;
      background: peachpuff;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
      width: 300px;
   }
</style>
</head>
<body>
   <div>
      <ul>
         <li>One</li>
         <li>Two</li>
         <li>Three
      </ul>
   </div>
</body>
</html>
廣告