html - "display: contents"属性值是如何工作的?

标签 html css css-selectors

我正在使用 display:contents 属性值与 element > element 选择器配对。 According to W3Schools , display: contents 属性值

Makes the container disappear, making the child elements children of the element the next level up in the DOM

(强调我的)。

所以我有这个示例代码:

.wrapper {
  background-color: red;
}

.hidden {
  display: contents;
}

.wrapper > .child {
  background-color: yellow;
}
<div class='wrapper'>
  <div class='hidden'>
    <div class='child'>I'm a child</div>
    <div class='child'>I'm a child</div>
  </div>

  <div class='child'>I'm a child</div>
  <div class='child'>I'm a child</div>
</div>

我希望所有的 child 都有黄色背景,因为 element> 元素 选择器应该将它们全部定位(当属性 display: contents 开始发挥作用)。

为什么不是这样? CSS 无法以这种方式定位 child 吗?

最佳答案

来自官方 CSSWG specification :

contents

The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes and text runs as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced in the element tree by its contents (including both its source-document children and its pseudo-elements, such as ::before and ::after pseudo-elements, which are generated before/after the element’s children as normal).

Note: As only the box tree is affected, any semantics based on the document tree, such as selector-matching, event handling, and property inheritance, are not affected. [...]

粗体部分(强调我的)是您正在寻找的答案。

还要注意这句话:“必须被视为好像它在元素树中已被其内容替换”。所以元素并没有真正被删除,但为了更容易解释,它就像元素被删除并被其内容替换。


PS:避免使用 www.w3schools.com作为像这样的准确定义的官方引用。它们可以很好地解释一般事物,但往往无法给出精确和准确的定义。

关于html - "display: contents"属性值是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440586/

相关文章:

javascript - 使用 fabric.js 在 Canvas 中保存 JSON

javascript - 如何循环遍历向下三层嵌套的 div 的子级

CSS :hover for empty cells :empty Selector

css - CSS 跨浏览器外观有问题

javascript - CSS:我怎样才能有一个 "scatter display of words"而不是 html 默认显示向上/向下?

css - :nth-child For Nested Elements

javascript - javascript 或 jquery 中的 nth-child 等效项

java - 如何在 Mac OS 10.6.6 上运行 Java Applet

html - 将宽度 100% 设置为两个固定宽度 div 中间的 div,全部位于另一个 100% 宽度 div 内

php - 如何从 PHP 生成的输出中获取漂亮的 HTML 源代码?