CSS 选择class所有子元素和选择class下所有元素

2,617 阅读1分钟

1.选择class下所有子元素

.class>* 选择器可以选择class类名下的所有子元素,注意,只能选择第一级子元素,不能递归选择,示例如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="main">
        <div class="first" style="width: 300px;height: 300px;">
            <div class="second" style="width: 200px;height: 200px;">
                <div class="three" style="width: 100px;height: 100px;">

                </div>
            </div>
        </div>
        <div style="width: 300px;height: 300px;"></div>
        <div style="width: 300px;height: 300px;"></div>
    </div>
    <style>
        .main>* {
            border: 1px blue solid;
        }
    </style>
</body>

</html>

展示效果

子元素选择器.png

2.选择class下所有元素

.class * 则可以选择class下的所有元素,示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="main" style="width: 400px;height: 400px;">
        <div class="first" style="width: 300px;height: 300px;">
            <div class="second" style="width: 200px;height: 200px;">
                <div class="three" style="width: 100px;height: 100px;">

                </div>
            </div>
        </div>
    </div>
    <style>
       .main  * {
            border: 1px blue solid;
        }
    </style>
</body>

</html>

所有子元素.png