当父元素设置了 overflow:hidden 属性时,子元素的 border-radius 会受到父元素背景的影响。

7
这是我的一个问题的扩展,之前我在问题上提出过。不过这次问题更加具体且更接近我正在努力解决的实际情况。
如果一个元素嵌套在另一个元素内,且父元素和子元素都有边框半径,并且父元素的背景与子元素的背景不同,那么父元素的背景就会在子元素的圆角周围显现出来。
如果父元素使用了overflow: hidden属性,则使子元素的边框半径小于父元素的边框半径的解决方法将不再有效。
CodePen示例:http://codepen.io/azangru/pen/pgmOvJ(请注意黄色背景从子元素的黑色背景下方显示出来)。
Html:
<div class="dark-bg">
  <div class="outer">
    <div class="middle">
      <div class="inner">
      </div>
    </div>
    <div class='some-text'>
      This is text. There can be quite a decent amount of text here, so the outer div needs to have overflow: hidden. Like this, you see?
    </div>
  </div>
</div>

CSS(层叠样式表):
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.dark-bg {
  height: 100%;
  width: 100%;
  padding-top: 10px;
  background: black;
}

.outer {
  width: 200px;
  height: 200px;
  margin: auto;
  background: white;
  border-radius: 10px;
  overflow: hidden;
}

.middle {
  width: 100%;
  height: 50%;
  background: yellow;
  border-radius: 10px 10px 0 0;
}

.inner {
  width: 100%;
  height: 100%;
  background: black;
  border-radius: 10px 10px 0 0;
}
.some-text {
  margin-top: 20px;
  padding: 0 10px;
}

有没有办法让子元素的背景完全覆盖父元素的背景?
(当然,一个显而易见的解决方案是从父元素中移除 overflow: hidden 属性,并为文本添加另一个容器,该容器将使用 overflow: hidden。然而,如果可能的话,我真的不想采用这种方法)
1个回答

4
这是因为背景边框进行了抗锯齿处理,因此会允许一定量的混合。可以通过将 transform: translateZ(0px) 应用于内部元素来减轻其可见度。一种不太通用但更有效的解决方案是在内部应用阴影。另外,似乎使用克隆基本元素属性的伪元素也可以解决这个问题。

/*
.inner {
    box-shadow: 0px 0px 0px 1px black;  
}
*/


html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.dark-bg {
  height: 100%;
  width: 100%;
  padding-top: 10px;
  background: black;
}

.outer {
  width: 200px;
  height: 200px;
  margin: auto;
  background: white;
  border-radius: 10px;
  overflow: hidden;
}

.middle {
  width: 100%;
  height: 50%;
  background: yellow;
  border-radius: 10px 10px 0 0;
}

.inner {
  width: 100%;
  height: 100%;
  background: black;
  border-radius: 10px 10px 0 0;
  position: relative;
}

.inner:after {
  content: "";
  position: absolute;
  background-color: inherit;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
}
.some-text {
  margin-top: 20px;
  padding: 0 10px;
}
<div class="dark-bg">
  <div class="outer">
    <div class="middle">
      <div class="inner">
      </div>
    </div>
    <div class='some-text'>
      This is text. There can be quite a decent amount of text here, so the outer div needs to have overflow: hidden. Like this, you see?
    </div>
  </div>
</div>


“box-shadow”解决方案对我不起作用,因为我不能指望背景是黑色的。 “transform: translateZ(0px)”方法很有趣,谢谢您提供这个方法。 - azangru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接