css - 根据另一个固定 flex 列的宽度

标签 css flexbox

我有一个 500px 和 2 列的包装器。第二列是 200px 宽度(flex: 0 0 200px)。

如果第一个元素> 300px第一列将根据这个元素扩展。

如何仅根据包装器和第二列的宽度来阻止第一列增长?

在这里 fiddle :https://jsfiddle.net/b58aatdr/3/

#hello {
  display: flex;
  width: 500px;
}
#hello > div {
  height: 50px;
}
#hello > div:first-child {
  background-color: yellow;
}
#hello > div:last-child {
  background-color: red;
  flex: 0 0 200px;
}
#baddiv {
  width: 400px;
  height: 20px;
  background-color: purple;
}
<div id="hello">
  <div>
    <div id="baddiv"></div>
  </div>
  <div></div>
</div>

最佳答案

设置 max-width: 300px 到你的第一个 div 如果你想让它自己调整到 300px 并且使用 width: 300px; 如果你想要它总是300 像素,即使内容不太宽。

根据评论更新

2:nd div 组使用了另一个技巧,position: absolute,其中不需要设置任何宽度,它使用父级和右侧的 div 来限制左侧的 div 增长超过 300px。

另请注意,这是元素工作方式的正常行为,如果它们没有设置固定/最大宽度,它们会增长(或在某些情况下换行)以适应其内容。

根据评论更新 2

3:rd div 组使用display: table 而不是flex,其中不需要设置任何宽度。

.hello {
  display: flex;
  width: 500px;
}
.hello > div {
  height: 50px;
}
.hello > div:last-child {
  background-color: red;
  flex: 0 0 200px;
}
.baddiv {
  width: 400px;
  height: 20px;
  background-color: purple;
}

/* alt. 1 */
.hello.nr1 > div:first-child {
  background-color: yellow;
  max-width: 300px;
}

/* alt. 2 */
.hello.nr2 > div:first-child {
  flex: 1;
  position: relative;
  background-color: lime;
}
.inner {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

/* alt. 3 */
.hello.nr3 {
  display: table;
  table-layout: fixed;
  width: 500px;
}
.hello.nr3 > div {
  height: 50px;
  display: table-cell;
}
.hello.nr3 > div:first-child {
  background-color: cyan;
}
.hello.nr3 > div:last-child {
  background-color: red;
  width: 200px;
}
<div class="hello nr1">
  <div>
    <div class="baddiv"></div>
  </div>
  <div></div>
</div>

<br>

<div class="hello nr2">
  <div>
    <div class="inner">
      <div class="baddiv">
      </div>
    </div>
  </div>
  <div></div>
</div>

<br>

<div class="hello nr3">
  <div>
    <div class="baddiv"></div>
  </div>
  <div></div>
</div>

关于css - 根据另一个固定 flex 列的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805855/

相关文章:

javascript - 下拉菜单点击关闭

css - Flexbox: flex 增长问题

html - Safari 中具有显示 flex 的按钮高度不统一

CSS 选择器链性能

html - 如何布局跨越两个不同背景图像的图像的方法

CSS 下拉菜单,清除第一个 lvl 悬停

html - 如何修复 Windows Safari 5.1.7 中的 flexbox ?

css - 在输入元素下方放置标签描述

CSS Flex Box Gallery 问题

javascript - 停止相对 div 滚动到某个点