【发布时间】:2019-12-06 15:08:15
【问题描述】:
这可能是重复的,但我已经在 stackoverflow 上解决了大约 20 个“flexbox overflowing children”问题,但没有找到我的具体问题的答案......所以如果这个 is 重复并且有人已经回答了这个特定的问题,我真的非常感谢一个链接:)提前感谢您的任何建议:)
我正在设计一个预先生成的表单,在这种情况下更改 html 是不切实际的。 必须是一个简单的,我不敢相信我忽略了那个!这个css解决方案...
我对这种样式的意图是,如果可能的话,我希望每个单独的标签都保持在一行上,而不是挤压得更窄和环绕。如果这意味着一个单选按钮 + 标签延伸了表单的整个宽度,那很好,但我只希望标签(加上单选输入)比表单宽。同时,如果表单项 div 不能全部放在一行上,我希望它们在必要时换行。我正在使用嵌套的弹性框,因为我希望能够垂直居中我的单选按钮和标签。不幸的是,根据包含元素的宽度,“form-item” div 会挤压自己以完全适合一行,并且其中的标签会溢出!
我已将表单简化为一个非常基本的测试用例。你可以see it on codepen。这是html和scss:
html:
<form>
<div class="container">
<div class="form-item form-item--1">
<input type='radio' id='item1' name='group'>
<label for='item1'>The quick brown fox</label>
</div>
<div class="form-item form-item--2">
<input type='radio' id='item1' name='group'>
<label for='item1'>The quick brown fox</label>
</div>
<div class="form-item form-item--3">
<input type='radio' id='item1' name='group'>
<label for='item1'>The quick brown fox</label>
</div>
<div class="form-item form-item--4">
<input type='radio' id='item1' name='group'>
<label for='item1'>The quick brown fox</label>
</div>
</div>
</form>
scss:
.container {
// setting the container div to a width that provokes this issue...
max-width: 45em;
// the form-item child divs should be wrapping at this width, but instead their contents are overflowing!!!
display: flex;
flex-wrap: wrap;
}
.form-item {
// put 20px between this element and the next element to the right
margin-right: 20px;
// make each div at least as wide as its content, and have them expand to fill all available space.
flex: 1 0 auto;
display: flex; // <-- If the form-item divs are not flexboxes, the contents do *not* overflow. Instead the last div wraps as desired. Of course, then the contents are not vertically centered, and the flex-bases of the input and labels are ignored. For those reasons, I *really* want to use display: flex here!!!
input {
// make the radio button take up exactly 25px of horizontal space
flex: 0 0 25px;
}
label {
// make the label at least as wide as its content, and have it expand to fill all available space.
flex: 1 0 auto;
}
}
// styling to better display the situation, but shouldn't affect the issue. (You can comment all the following out, and the labels are still overflowing their form-item parent div)
html {
font-size: 62.5%;
}
body {
font-size: 16px;
}
.container {
align-items: center;
border: 1px dashed black;
height: 100px;
}
.form-item {
align-items: center;
border: 1px dashed green;
height: 50px;
label {
border: 1px dashed orange;
}
}
【问题讨论】:
-
设置
.form-item label { flex: 1;} -
@Awais,谢谢,但这并不是我想要的效果... flex: 1 相当于 flex-grow: 1、flex-shrink: 1 和 flex-basis: auto .所以标签会根据需要缩小,标签文本最终会包裹在标签内,而不是表单项 div 换行。看起来 Artur 找到了一个可行的解决方案,但我不知道它为什么会起作用!!!如果您有任何见解,也许可以评论他的解决方案,因为我很想知道它为什么有效:)