如何使用 CSS 選擇元素的所有子元素,除了最後一個子元素?


為了使用 CSS 選擇元素的所有子元素,除了最後一個子元素,我們將瞭解兩種不同的方法。每種方法都將使用CSS 偽類選擇器來執行所需的任務。

在本文中,我們將瞭解如何使用不同的方法在CSS 中選擇元素的所有子元素,除了最後一個子元素。我們將詳細討論每種方法,並提供示例來幫助您理解它們的工作原理。

選擇元素的所有子元素,除了最後一個子元素的方法

以下列出了使用 CSS 選擇元素的所有子元素,除了最後一個子元素的方法,我們將在本文中逐步解釋並提供完整的示例程式碼。

使用 :not 選擇器

在第一種方法中,選擇元素的所有子元素,除了最後一個子元素,涉及使用:not() 偽類選擇器和:last-child 偽類選擇器。

  • 我們使用 CSS :last-child 偽類選擇器,它選擇元素的最後一個子元素。
  • 我們將使用 CSS :not() 偽類選擇器,它將選擇所有不匹配指定選擇器的元素。
  • 我們將使用 ':last-child' 以及 ':not()' 來選擇元素的所有子元素,除了最後一個子元素。
  • 我們使用了 '.parent > *:not(:last-child)',它將選擇 .parent 類元素的所有直接子元素,除了最後一個子元素。

示例

這是一個完整的示例程式碼,實現了上述步驟,以選擇元素的所有子元素,除了最後一個子元素。

<!DOCTYPE html>
<html>
<head>
    <title>
        To select all children of an element
        except the last child using CSS.
    </title>
    <style>
        .parent>*:not(:last-child) {
            color: green;
        }
    </style>
</head>
<body>
    <h3>
        To select all children of an element
        except the last child using CSS.
    </h3>
    <p>
        In this example we have used :not() selector
        and :last-child selector to select all
        children of an element except the last child.
    </p>
    <div class="parent">
        <h4>First Child</h4>
        <h4>Second Child</h4>
        <p>Third Child</p>
        <span>Fourth Child</span>
    </div>
</body>
</html>

使用 :nth-last-child() 選擇器

在這種方法中,我們使用 CSS nth-last-child() 偽類選擇器,它根據元素在元素子元素列表中的位置選擇元素。

  • 我們使用 '.parent > *:nth-last-child(n+2)' 來選擇除最後一個子元素之外的所有子元素。
  • 我們指定了引數 n+2。指定的引數使用 CSS 選擇 HTML 中的所有元素,除了最後一個子元素,即從末尾開始的第一個子元素。
  • 我們使用了 CSS 屬性,例如:背景顏色填充顏色圓角寬度文字修飾字體系列邊框 來設定所有按鈕的樣式,除了最後一個按鈕。

示例

這是一個完整的示例程式碼,實現了上述步驟,以選擇元素的所有子元素,除了最後一個子元素。在這個示例中,我們為每個按鈕應用了樣式,除了最後一個按鈕。

<!DOCTYPE html>
<html>
<head>
    <title>
        To select all children of an element
        except the last child using CSS.
    </title>
    <style>
        .parent>*:nth-last-child(n+2) {
            background-color: green;
            padding: 10px;
            color: white;
            border-radius: 10px;
            width: 10em;
            text-decoration: none;
            font-family: sans-serif;
            border: none;
        }
    </style>
</head>
<body>
    <h3>
        To select all children of an element
        except the last child using CSS.
    </h3>
    <p>
        In this example we have used :nth-last-child()
        selector to select all children of an element
        except the last child.
    </p>
    <div class="parent">
        <button>First</button>
        <button>Second</button>
        <button>Third</button>
        <button>Fourth</button>
    </div>
</body>
</html>

結論

在本文中,我們瞭解瞭如何選擇元素的所有子元素,除了最後一個子元素。我們實現了兩種不同的方法:使用 CSS :not() 選擇器:nth-last-child() 選擇器。上面討論的兩種方法都說明了 CSS 如何在為元素的所有子元素應用不同的樣式,除了最後一個子元素。

更新於:2024年8月5日

12K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告