CSS选择前面的兄弟

在CSS中,我们可以使用相邻兄弟选择器(Adjacent sibling combinator)和通用兄弟选择器(General sibling combinator)来选择一个元素前面的兄弟元素。

相邻兄弟选择器

相邻兄弟选择器用于选取指定元素后面紧接的同级元素。它的语法为 E + F,其中 E 为要选择的元素,F 为紧接在 E 后面的同级元素。

示例

假设我们有以下的HTML结构:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Adjacent sibling selector example</title>
<style>
    p + p {
        color: blue;
    }
</style>
</head>
<body>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
</body>
</html>

在上面的示例中,我们使用了相邻兄弟选择器来选取第一个段落后面紧接的第二个段落,为它设置了颜色为蓝色。因此,第一个段落后面的第二个段落会显示为蓝色。

运行结果

This is the first paragraph.
This is the second paragraph.
This is the third paragraph.

通用兄弟选择器

通用兄弟选择器用于选取指定元素之后的所有同级元素。它的语法为 E ~ F,其中 E 为要选择的元素,F 为跟在 E 之后的同级元素。

示例

假设我们有以下的HTML结构:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>General sibling selector example</title>
<style>
    p ~ p {
        color: red;
    }
</style>
</head>
<body>
    This is the first paragraph.
    This is the second paragraph.
    This is the third paragraph.
</body>
</html>

在上面的示例中,我们使用了通用兄弟选择器来选取第一个段落后面的所有段落,为它们设置了颜色为红色。因此,第一个段落后面的所有段落都会显示为红色。

运行结果

This is the first paragraph.
This is the second paragraph.
This is the third paragraph.

总结

通过相邻兄弟选择器和通用兄弟选择器,我们可以方便地选择某个元素前面或之后的兄弟元素,并对它们进行样式设置。这两种选择器在实际开发中有着广泛的应用,能够帮助我们更灵活地控制页面元素的样式。

最后修改:2024 年 05 月 17 日
如果觉得我的文章对你有用,请随意赞赏