gpt4 book ai didi

css - 使元素占用可用的水平空间而不导致其父元素变宽

转载 作者:行者123 更新时间:2023-11-28 14:26:05 27 4
gpt4 key购买 nike

我有一个 flexbox 容器,正好有两个子容器,它们都可以有可变内容。我希望整个容器的宽度适合第一个子项的宽度,但我希望第二个子项的内容可以换行并且不会导致容器水平增长。请参阅下面的可运行代码段以获取视觉问题描述。

目前正在寻找 CSS 网格解决方案。我找到了一个部分解决方案,但依赖于 JavaScript:将第二个 child 设为相对容器,将其内容放在中间的绝对定位容器中,并使用 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>

最佳答案

只需设置.secondmin-widthwidth:

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

.child {
background-color: wheat;
}

.second {
margin-top: 10px;
min-width: 100%;
width: 0;
}
<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>

关于css - 使元素占用可用的水平空间而不导致其父元素变宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com