一行中的 Flex 项目以不同的宽度呈现

Lab*_*ino 5 html css google-chrome flexbox

我在 html 中使用 css flexbox 创建了 3 个盒子,但 Chrome 正在渲染不同大小的盒子。

在此输入图像描述

拖动浏览器的边框使视图变小。

感谢您的帮助!

代码笔: https: //codepen.io/labanino/pen/rGaNLP

body {
  font-family: Arial;
  font-size: 2rem;
  text-transform: uppercase;
}

.flex {
  height: 200px;
  display: flex;
  flex-direction: row;
}

.flex>section {
  flex: 1 1 auto;
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
}

.flex>section:nth-child(1) {
  background: brown;
  margin-right: 20px;
  border: 1px solid #999;
}

.flex>section:nth-child(2) {
  background: pink;
  margin-right: 20px;
  border: 1px solid #999;
}

.flex>section:nth-child(3) {
  background: green;
  margin-right: 0;
  border: 1px solid #999;
}
Run Code Online (Sandbox Code Playgroud)
<div class="flex">
  <section>Brown</section>
  <section>Pink</section>
  <section>Green</section>
</div>
Run Code Online (Sandbox Code Playgroud)

Spa*_*cus 7

不要auto在您的项目的 flex 属性中使用。使用 100%,这将调整弹性框中的宽度,并根据您添加的任意数量的元素进行调整(如果您想要添加超过 3 个元素)。

.flex > section {
  flex: 1 1 100%;  
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
}
Run Code Online (Sandbox Code Playgroud)

它们尺寸不同的原因是当您使用 时auto,它的宽度基于盒子的内容。这就是为什么中间的宽度不那么宽,因为“粉红色”一词比“绿色”一词占用的空间更少。