为什么我的 Flex 项目没有占据 Flex 容器的整个宽度?

问题描述 投票:0回答:1

我里面有一个大的柔性容器和两个小的柔性容器。两个小型柔性容器各有两个柔性项目。我面临的问题是第二个小弹性容器内的两个弹性项目没有占据第二个小弹性容器的整个宽度。

Image of one big flex container containing two small flex containers each containing two flex items. A black arrow points to a red column streak of pixels in the second small flex container, the red column streak of pixels is at the right-end of the second small flex container. The code is rendered on Safari Version 16.6.1

.BIG-flex-container {
  display: flex;
}

.SMALL-flex-container {
  min-width: 50%;
  max-width: 50%;
  display: flex;
  background-color: red;
  overflow: scroll;
}

.flex-item {
  min-width: 100%;
  max-width: 100%;
  height: 300px;
}

.flex-item-1 {
  background-color: blue;
}

.flex-item-2 {
  background-color: green;
}
<div class="BIG-flex-container">
  <div class="SMALL-flex-container">
    <div class="flex-item flex-item-1">
    </div>
    <div class="flex-item flex-item-2"></div>
  </div>
  <div class="SMALL-flex-container">
    <div class="flex-item flex-item-1">
    </div>
    <div class="flex-item flex-item-2"></div>
  </div>
</div>

隐藏溢出确实会消除列条纹,但会阻止我的第二个小弹性容器可滚动。我还使用 JavaScript 以编程方式滚动第二个小 Flex 容器,同时隐藏溢出,但条纹返回了!我期望的是我的弹性项目完美地填充我的第二个小弹性容器,而第二个小弹性容器的背景颜色不显示。

html css flexbox scroll containers
1个回答
0
投票

诸如此类的伪影确实时常发生。它们通常在某些视口配置中可见,而在其他视口配置中则不可见。如果您调整浏览器窗口的大小,我想您会发现此工件以某些尺寸存在,但并非所有尺寸都存在。浏览器以分数像素计算宽度和高度,但在渲染时,这些值必须四舍五入为整个像素。我们已经知道这个问题很多年了,但没有解决方案。忽略它即可,您的代码没有任何问题。通过仔细选择背景颜色来最大程度地减少影响。

不过,我想建议对您的代码进行不相关的改进。一个更简洁的解决方案(在我看来)是设置

min-width: 100%
max-width: 100%
,而不是组合使用
width: 100%
flex-shrink: 0
来防止弹性项目收缩。

.BIG-flex-container {
  display: flex;
}

.SMALL-flex-container {
  width: 50%;
  display: flex;
  background-color: red;
  overflow: scroll;
}

.flex-item {
  width: 100%;
  height: 300px;
  flex-shrink: 0;
}

.flex-item-1 {
  background-color: blue;
}

.flex-item-2 {
  background-color: green;
}
<div class="BIG-flex-container">
  <div class="SMALL-flex-container">
    <div class="flex-item flex-item-1">
    </div>
    <div class="flex-item flex-item-2"></div>
  </div>
  <div class="SMALL-flex-container">
    <div class="flex-item flex-item-1">
    </div>
    <div class="flex-item flex-item-2"></div>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.