此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

后续兄弟选择器

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

后续兄弟选择器~)将两个选择器分开,并匹配第二个选择器的所有迭代元素,位置无须紧邻于第一个元素,只须有相同的父级元素

css
/* 在任意图像后的兄弟段落 */
img ~ p {
  color: red;
}

语法

css
former_element ~ target_element { style properties }

示例

CSS

css
p ~ span {
  color: red;
}

HTML

html
<span>This is not red.</span>
<p>Here is a paragraph.</p>
<code>Here is some code.</code>
<span>And here is a red span!</span>
<span>And this is a red span!</span>
<code>More code…</code>
<div>How are you?</div>
<p>Whatever it may be, keep smiling.</p>
<h1>Dream big</h1>
<span>And yet again this is a red span!</span>

结果

规范

Specification
Selectors Level 4
# general-sibling-combinators

浏览器兼容性

参见