如何选择特定类的最后一个元素

用 CSS 解决

要选择特定类的最后一个元素,我们可以使用 CSS :last-of-type 伪类。

在这个片段中,我们将展示带有 HTML <article> 和 <p> 元素的示例。

选择特定类的最后一个 <article> 元素的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        background: #95ada2;
      }
      .comment {
        width: 470px;
        border: 1px solid #ffffff;
        padding: 10px;
        border-bottom: 2px dotted #f0f0f0;
        margin-bottom: 10px;
      }
      .comment:last-of-type {
        border-bottom: 3px dashed lightblue;
        margin-bottom: 0;
      }
    </style>
  </head>
  <body>
    <div class="commentList">
      <article class="comment"></article>
      <article class="comment"></article>
      <article class="comment"></article>
      <div class="text"> hello </div>
    </div>
  </body>
</html>

选择特定类的最后一个 <p> 元素的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .text:last-of-type {
        background: purple;
        font-style: italic;
        color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <h1>Example of :last-of-type selector </h1>
    <p class="text">Paragraph number 1.</p>
    <p class="text">Paragraph number 2.</p>
    <p class="text">Paragraph number 3.</p>
    <p class="text">Paragraph number 4.</p>
  </body>
</html>
日期:2020-06-02 22:15:12 来源:oir作者:oir