溢出隐藏导致 div 在下面浮动 div 而不是在它后面

Overflow hidden causes div to be underneath floated div instead behind it

目前我遇到的情况是两个div相邻(在一个容器下div),一个向左浮动,另一个占其父级的100%。

我还希望隐藏滚动条,但内容将保持裁剪状态(通过 overflow: hidden 设法实现了这一点)。但是,当我使用 overflow: hidden 时,浮动排列发生了变化,div 位于浮动的下方。

这是隐藏和不隐藏滚动条的层次结构片段:

.d1{
    background: red;
    height: 100%;
    width: 20px;
    position: relative;     
    transition: width 0.5s;
    float: left;
}

.cont{
    height: 50px;
    width: 100px;
    background: yellow;
}

.d2{
    background: blue;
    overflow: hidden;
    height: 100%;
    width: 100%;
}

.d3{
    background: blue;
    height: 100%;
    width: 100%;
}
<h1>Without overflow:</h1>
<div class="cont">
  <div class="d1"></div>
  <div class="d3"></div>
</div>

<h1>With overflow:</h1>
<div class="cont">
  <div class="d1"></div>
  <div class="d2"></div>
</div>

我想满足这两个约束条件(浮动一个 div 在另一个后面,100% 占用父 ANF 隐藏滚动条但保持剪裁)。

我能够通过使用 position: absolutecss grid 获得预期的结果,但我想避免使用这些解决方案。

谢谢。

而不是 overflow:hidden 使用 clip-path:inset(0)。两者都应该通过裁剪溢出的内容产生相同的结果

.d1 {
  background: red;
  height: 100%;
  width: 20px;
  position: relative;
  z-index:1;
  transition: width 0.5s;
  float: left;
}

.cont {
  height: 50px;
  width: 100px;
  background: yellow;
}

.d2 {
  background: blue;
  clip-path:inset(0);
  height: 100%;
  width: 100%;
}
<h1>With overflow:</h1>
<div class="cont">
  <div class="d1"></div>
  <div class="d2"></div>
</div>

我想稍微解释一下为什么你有隐藏溢出的问题。

没有overflow: hidden

d1和d3重叠,因为d1设置为float: left.

为什么d1在d3前面?这是因为d1设置了position: relative和float,使得它的栈序更大

overflow: hidden

使用 overflow 属性 的值不同于 visible(它的默认值)将创建一个新的块格式化上下文,并且它不会与 float 元素重叠,而是跟在前一个元素之后。

例如设置d2的宽度小于80px(100-20)会让d2出来d1

.d1 {
  background: red;
  height: 100%;
  width: 20px;
  position: relative;
  transition: width 0.5s;
  float: left;
}

.cont {
  height: 50px;
  width: 100px;
  background: yellow;
}

.d2 {
  background: blue;
  overflow: hidden;
  height: 100%;
  width: 80px;
}
<h1>With overflow:</h1>
<div class="cont">
  <div class="d1"></div>
  <div class="d2"></div>
</div>