首页 > 解决方案 > `position: fixed` 是否会破坏混合混合模式,是否有解决方法?

问题描述

我试图让盒子阴影在不同的背景下很好地发挥作用。标准方法似乎是使用混合混合模式,并在真实的 div 后面应用一个假 di​​v 并产生效果。

此处是此技术的一个示例(单击右上角的 + 图标)。

如果我稍微更改此代码以将非背景元素包装到一个容器中,position: fixed它会中断,例如此处。注意,position: absolute工作正常。

我确实需要一个像示例这样的结构,一个position-fixed可以容纳可变高度或宽度以及.box元素的多个实例的混合父级。我可以粗略地猜测一下它为什么不起作用(已修复将其从文档流中分离出来,因此没有什么可以混合的),但我看不出解决方法。

我做的另一个例子减少了一些事情,注意如果你注释掉position-fixed它是如何工作的:

.blend {
  height: 100%;
  box-shadow: 0 4px 8px 0 rgba(156, 156, 156, 0.7);
  mix-blend-mode: multiply;
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
}

.box {
  background: grey;
  min-height: 10px;
  width: 100%;
  position: relative;
  margin: 0 0 15px;
}

.container {
  /* using absolute works */
  position: absolute;
  /* using fixed does not work */
  position: fixed;
  height: 50%;
  width: 50%;
}

html {
  height: 100%;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  margin: 0;
}

.column {
  position: relative;
  width: 50%;
  height: 100%;
}

.left {
  background: #2D2D2D;
}

.right {
  background: #f6f6f6;
}
<div class="column left"></div>
<div class="column right"></div>

<div class="container">
  <div class="box">
    text
    <div class="blend"></div>
  </div>
  <div class="box">
    text<br /><br />more text
    <div class="blend"></div>
  </div>
</div>

(我看到了一个先前的问题,看起来类似,但我无法让他们的示例进行检查)

标签: css

解决方案


您可以将混合元素移出容器并将其固定为与容器相同的尺寸。

签出片段:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

html{
  height:100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  margin: 0;
}

.column {
  position: relative;
  width: 50%;
  height: 100%;
}

.left {
  background: #2D2D2D;
}

.right {
  background: #f6f6f6;
}

.blend {
  box-shadow: 0 4px 8px 0 rgba(156, 156, 156, 0.7);
  mix-blend-mode: multiply;
  position: fixed;
  height: 50%;
  width: 50%;
}

.box {
  background: grey;
  height: 100%;
  width: 100%;
  position: absolute;
}

.container {
  position: fixed;
  height: 50%;
  width: 50%;
}


</style>
</head>
<body>

<div class="column left"></div>
<div class="column right"></div>

<div class="blend"></div>
<div class="container">
	
  <div class="box">
    text
  </div>
</div>

</body>
</html>


推荐阅读