首页 > 解决方案 > 停止 flexbox 项目 "flex:1" 占用由子宽度引起的更多空间

问题描述

我有以下 html/css。呈现如下:

.parent {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}

.one {
  flex: 1;
  background-color: green;
}

.two {
  flex: 1;
  /* width: 100px; <-- this is what I'd like to achieve */
  background-color: yellow;
}

.inner {
  width: 150px; /* <-- this is bigger than width of .parent */
  height: 50px;
  background-color: blue;
}
<div class="parent">
  <div class="one"></div>
  <div class="two">
    <div class="inner"></div>
  </div>
</div>

在此处输入图像描述

如您所见,withdiv导致其父 div 使用 flex: 1 占用更多空间。.inner150px

我想要实现的是:

在此处输入图像描述

我知道存在并尝试使用,flex-grow并且flex-shrink. 我无法让它工作。

问题:有没有办法让它只使用 flexbox 工作?

标签: cssflexboxwidth

解决方案


position: relative一次性轻松管理two_position:absoluteinner

.parent {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}

.one {
  flex: 1;
  background-color: green;
}

.two {
  position: relative;
  flex: 1;
  /* width: 100px; <-- this is what I'd like to achieve */
  background-color: yellow;
}

.inner {
  position:absolute;
  width: 150px; /* <-- this is bigger than width of .parent */
  height: 50px;
  background-color: blue;
}
<div class="parent">
  <div class="one"></div>
  <div class="two">
    <div class="inner"></div>
  </div>
</div>

max-width:50%在课堂上使用two

演示 2

.parent {
  display: flex;
  width: 200px;
  height: 100px;
  background-color: red;
}

.one {
  flex: 1;
  background-color: green;
}

.two {
  flex: 1;
  max-width: 50%;
  /* width: 100px; <-- this is what I'd like to achieve */
  background-color: yellow;
}

.inner {
  width: 150px; /* <-- this is bigger than width of .parent */
  height: 50px;
  background-color: blue;
}
<div class="parent">
  <div class="one"></div>
  <div class="two">
    <div class="inner"></div>
  </div>
</div>


推荐阅读