CSS 兄弟选择器(选择所有兄弟)

CSS sibling selectors (select all siblings)(CSS 兄弟选择器(选择所有兄弟))
本文介绍了CSS 兄弟选择器(选择所有兄弟)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

通常,我擅长 CSS,但我似乎无法弄清楚这一点.如果我的结构是

<h2 class="open">1</h2><h2>2</h2><h2>3</h2><h2>4</h2><h2>5</h2></div>

如何使用带有 CSS 的 .open 类来定位所有同级 h2?我的主要问题是兄弟选择器(.open + h2)只会针对紧随 .open 之后的 h2.

解决方案

你可以使用 ~ 代替 + 选择以下所有兄弟:

.open ~ h2

如果您需要选择所有不是 .openh2 元素,无论它们在 .open 之前还是之后,都没有同级组合器.你需要使用 :not() 代替:

h2:not(.open)

如果您需要将选择限制为 div 父母,则可以选择使用子组合器:

div >h2:not(.open)

Usually, I'm good with CSS, but I can't seem to figure this one out. If I have a structure of

<div>
    <h2 class="open">1</h2>
    <h2>2</h2>
    <h2>3</h2>
    <h2>4</h2>
    <h2>5</h2>
</div>

how can I target all of the sibling h2s using the .open class with CSS? My main issue is that sibling selectors (.open + h2) will only target the h2 immediately following .open.

解决方案

You can select all the following siblings using ~ instead of +:

.open ~ h2

If you need to select all h2 elements that aren't .open whether they precede or follow .open, there is no sibling combinator for that. You'll need to use :not() instead:

h2:not(.open)

Optionally with a child combinator if you need to limit the selection to div parents:

div > h2:not(.open)

这篇关于CSS 兄弟选择器(选择所有兄弟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)
How to use coffeescript in developing web-sites?(如何在开发网站时使用coffeescript?)
Expose a javascript api with coffeescript(使用 coffeescript 公开一个 javascript api)
Coffeescript wrapping files in a function(Coffeescript 在函数中包装文件)
Multiple Files communication with coffeescript(与咖啡脚本的多个文件通信)