【发布时间】:2019-02-14 19:30:32
【问题描述】:
我有一个 flexbox 容器,其中正好有两个孩子,它们都可以有可变的内容。我希望整个容器的宽度适合第一个孩子的宽度,但我希望第二个孩子的内容能够换行并且 不 导致容器水平增长。请参阅下面的可运行 sn-p 以获得直观的问题描述。
目前正在寻找 CSS 网格解决方案。我找到了一个部分解决方案,但依赖于 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>
【问题讨论】:
-
我有点不清楚你在问什么。您是否希望两个框都不会占用超过 50% 的宽度?例如,像一张桌子?或者你想让第一个盒子占据至少 50% 的宽度,当它变大时缩小第二个盒子?你能画一幅画或以其他方式展示你想要得到的东西吗?您的代码“解决方案”看起来像两个相互堆叠的块。这可以通过
flex-wrap: wrap来完成。 -
听起来我也很熟悉..现在需要找到相关问题..
-
是否需要使用 Flexbox?
-
"在星号处换行到另一个不同的 div" 是无效的,所以你需要明确你的目标是什么。还有你为什么要使用
flex-direction:column,而你在这里显然需要flex-direction:row -
@BryceHowitson,这两个孩子是要垂直堆叠的。我以第二个代码sn-p的形式为你画了一张图,它产生的正是我想要的结果。