CSS教程
CSS进阶

CSS nth-​​child(n)

此选择器用于根据元素的位置匹配元素,而不管其父元素的类型如何。 n 可以是关键字,公式或数字。它用于根据元素在一组兄弟姐妹中的位置来匹配元素。它匹配每个元素,即第n个子元素。

语法

以下是此选择器的语法:
:nth-child(n) {
    //CSS Property
}
括号中的 " n" 是表示匹配元素模式的参数。可以是偶数或奇数的功能表示法。
奇数值表示位置在位置上像1、3、5等的奇数的元素。类似地,偶数值表示位置在偶数的元素依次为2、4、6等。
功能符号(An + B):功能符号表示兄弟姐妹的位置与 An + B 模式,其中 A 是整数步长, n 是从0开始的任何正整数,而 B 是整数偏移量。
让我们看一些插图。

示例1

在此示例中,我们使用功能符号 3n + 4 表示元素:
(3×0)+4 = 4,(3×1)+4 = 7,还有更多
<!DOCTYPE html>
<html>
<head>
    <title>CSS :nth-child Selector</title>
    <style>
    p:nth-child(3n+4) {
        background: yellow;
        color: black;
        font-size: 30px;
    }
    </style>
</head>
<body style="text-align:center">
    <h1>
        Hello World
    </h1>
    <h2>
        Welcome to the lidihuo
    </h2>
    <p>It will not affected.</p>
    <p>It will be affected.</p>
    <p>Not affected.</p>
    <p>Not affected.</p>
    <p>It will be affected.</p>
</body>
</html>
输出:
nth-child

Example2

在此示例中,我们将使用奇数和偶数关键字来匹配索引为奇数或偶数的元素。请注意,第一个子索引是1。
<!DOCTYPE html>
<html>
<head>
    <title>CSS :nth-child Selector</title>
    <style>
    p:nth-child(even) {
        background: yellow;
        color: black;
        font-size: 30px;
    }
    p:nth-child(odd) {
        background: blue;
        color: white;
        font-size: 20px;
    </style>
</head>
<body style="text-align:center">
    <h1>
        Hello World
    </h1>
    <h2>
        Welcome to the lidihuo
    </h2>
    <p>Odd</p>
    <p>Even</p>
    <p>Odd</p>
    <p>Even</p>
    <p>Odd</p>
</body>
</html>
输出:
nth-child
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4