使元素占用可用的水平空间而不会使其父元素变宽

时间:2019-02-14 19:30:32

标签: css flexbox css-grid

我有一个Flexbox容器,其中有两个孩子,两个孩子的内容都可以变化。我希望整个容器的宽度适合第一个孩子的宽度,但是我要包装第二个孩子的内容,并且使容器水平增长。有关视觉问题的说明,请参见下面的可运行代码段。

当前正在寻找CSS Grid解决方案。我找到了一个部分解决方案,但是它依赖于JavaScript:将第二个孩子作为一个相对容器,将其内容放在一个绝对定位的中间容器中,并使用JS设置固定高度。至少这对显示我的需求很有帮助。

问题:

.container {
  display: inline-flex;
  flex-direction: column;
  border: 1px solid red;
}

.child {
  background-color: wheat;
  margin: 5px;
}
<div class="container">
  <div class="first child">
    This content can grow and be as wide as it wants
  </div>
  <div class="second child">
    This content will also be any size it wants, but I * want it to wrap at the asterisk in this sentence, which is where the first child above would naturally end. This will be its own flexbox container holding several buttons that should wrap onto new rows.
  </div>
</div>

JavaScript /绝对解决方案:

let second = document.getElementsByClassName('second')[0]
let content = document.getElementsByClassName('absolute')[0]

second.style.height = content.offsetHeight + 'px'
.container {
  display: inline-flex;
  flex-direction: column;
  border: 1px solid red;
}

.child {
  background-color: wheat;
  margin: 5px;
}

.second {
  position: relative;
  /* height to be set by JS */
}

.absolute {
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
}
<div class="container">
  <div class="first child">
    This content can grow and be as wide as it wants
  </div>
  <div class="second child">
    <div class="absolute">
      This content is longer than the above but still wraps in the right place.
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

只需设置min-width的{​​{1}}和width

.second
.container {
  border: 1px solid red;
  display: inline-block;
  padding: 5px;
}

.child {
  background-color: wheat;
}

.second {
  margin-top: 10px;
  min-width: 100%;
  width: 0;
}