html - 在绝对定位元素上渲染的 CSS 滤镜效果

标签 html css

请考虑这个 HTML+CSS:

#testArea {
  box-sizing: border-box;
  width: 300px;
  height: 300px;
  background-color: blue;
  padding: 20px;
  color: white;
  font-weight: bold;
  font-size: 18px;
}
#testArea:hover {
  -webkit-filter: brightness(50%);
}
#absElement {
  position: absolute;
  left: 100px;
  top: 100px;
  width: 100px;
  height: 100px;
  background-color: green;
}
<div id="absElement"></div>
<div id="testArea">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</div>

如果您将鼠标悬停在蓝色区域上,:hover CSS 样式将启动并应用 50% 亮度滤镜。不知何故,绝对定位的绿色 absElement 消失了。我原以为 testArea 元素本身的呈现会发生变化,但似乎一种覆盖元素只是动态地呈现在宿主元素之上。

如果我将 z-index: 1 添加到 #absElement 样式定义中,那么行为就会符合我的预期。 “修复”它的另一种方法是将 absElement div 移动到 testArea div 之后。但奇怪的是我应该这样做,因为绝对定位的元素总是应该在流布局元素上呈现。

这是怎么回事?我知道我可以添加 z-index 属性然后继续,但我想了解滤镜效果是如何应用/呈现的。

最佳答案

来自filter specification :

A computed value of other than none results in the creation of a stacking context [CSS21] the same way that CSS opacity does.

然后从another specification你可以找到元素的“绘画顺序”:

Within each stacking context, the following layers are painted in back-to-front order:

  1. the background and borders of the element forming the stacking context.
  2. the child stacking contexts with negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  7. the child stacking contexts with positive stack levels (least positive first).

如果没有过滤器,您的元素将在步骤 (3) 中绘制,因为它不会创建堆叠上下文。所以它在 position:absolute 下在 (6) 绘制的元素

使用过滤器,您的元素也将在步骤 (6) 中绘制,在这种情况下,树顺序将被视为知道先绘制哪个元素,因此它将在 position:absolute 之上结束。一个。

您可以按照规范获取每个步骤的更精确细节。

关于html - 在绝对定位元素上渲染的 CSS 滤镜效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71726960/

相关文章:

CSS——如何干起来?

javascript - 如何只为子元素运行 jQuery 函数?

javascript - 使用 CSS 缩放 HTML 中的图像

html - 使文本保留在一个 div 中

jquery - Bootstrap 导航栏下拉菜单部分隐藏在 IE8 中 - 为什么?

javascript - 在粘性页脚布局中将视口(viewport)中的视频居中

html - 如何为图像添加混合模式?

javascript - 在angularjs中单击它时如何激活html元素?

html - 如何删除一组元素中最后一个子项的底部边距?

javascript - 浏览器未缓存的 Symfony assteic 资源