“〜”(波浪号/波浪形/旋转)CSS选择器是什么意思?

CSS

猿蛋蛋凯

2020-03-16

搜索~角色并不容易。我查看了一些CSS,发现了这个

.check:checked ~ .content {
}

这是什么意思?

第1678篇《“〜”(波浪号/波浪形/旋转)CSS选择器是什么意思?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
村村老丝 2020.03.16

请注意,在属性选择器(例如[attr~=value])中,波浪号

表示一个属性名称为attr的元素,其值是由空格分隔的单词列表,其中之一就是value

https://developer.mozilla.org/zh-CN/docs/Web/CSS/Attribute_selectors

理查德Harry 2020.03.16

还可以检查家庭中的其他组合器,并重新了解这个特定的组合器。

  • ul li
  • ul > li
  • ul + ul
  • ul ~ ul

清单示例:

  • ul li- 寻找内部 -选择所有li元件放置(任意位置)内的ul; 后代选择器
  • ul > li- 向内看 - 选择的直接li元素ul即它只会选择直接子女liul; 子选择器子组合器选择器
  • ul + ul- 向外看 -选择ul紧随其后的ul它不是在寻找内部,而是在寻找紧随其后的元素。相邻兄弟选择器
  • ul ~ ul- 向外看 -选择所有ul紧随其后的内容ul,但两者ul都应具有相同的父对象;通用兄弟选择器

我们在这里看到的是通用兄弟选择器

Sam梅小胖 2020.03.16

通用同级组合器

通用的同级组合器选择器与相邻的同级组合器选择器非常相似。不同之处在于,被选择的元素不需要立即在第一个元素之后,而是可以出现在其后的任何位置。

更多信息

小哥路易 2020.03.16

它是General sibling combinator在@萨拉曼的答案是很好的解释。

我做了小姐是Adjacent sibling combinator这是+和是密切相关的~

例子是

.a + .b {
  background-color: #ff0000;
}

<ul>
  <li class="a">1st</li>
  <li class="b">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="a">5th</li>
</ul>
  • 匹配的元素是 .b
  • 毗邻 .a
  • 之后.a在HTML

在上面的示例中,它将标记为2,li而不是4。

   .a + .b {
     background-color: #ff0000;
   }
<ul>
  <li class="a">1st</li>
  <li class="b">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="a">5th</li>
</ul>

JSFiddle

小小阿飞 2020.03.16

~选择器实际上是通用同级组合器(在选择器级别4中重命名为后续同级组合):

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Consider the following example:

.a ~ .b {
  background-color: powderblue;
}
<ul>
  <li class="b">1st</li>
  <li class="a">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="b">5th</li>
</ul>

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android