为什么在包装元素后flexbox不能缩小以适合其尺寸? [英] Why doesn't flexbox shrink to fit after wrapping elements?
问题描述
我希望有一个最大宽度可以超出该宽度的flex-box,但是它也适合flexbox中任何给定行的最大大小。
I want to have a flex-box with a maximum width that wraps beyond that width, but that also fits the maximum size of any given "row" within the flexbox.
我现在面临的问题是,任何超出最大宽度然后包裹的元素都会导致flexbox仍然占据该最大宽度。
The problem I am facing now is that any element that stretches beyond the maximum width and then wraps causes the flexbox to still take up that maximum width.
以下是指向该问题的Codepen的链接:
Here is a link to a codepen demonstrating the issue:
https://codepen.io/heroes-coding/pen/rNaGYmo
是顶部容器的html / css:
And here is the top container's html / css:
<div class="holder">
<div class="flexbox">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
body {
background: black;
}
.holder {
width: 650px;
background: gray;
margin-top: 50px;
}
.flexbox {
display: flex;
background: blue;
max-width: 500px;
width: fit-content;
flex-wrap: wrap;
}
.item {
width: 100px;
height: 50px;
background: red;
border-bottom: 1px dotted white;
border-top: 1px dotted white;
border-right: 1px dotted white;
}
.item.wide {
width: 200px;
}
我想让flexbox仍以500px包装,但要缩小以适合包装后的内容。
I'd like to have the flexbox still wrap at 500px but shrink to fit the content after the wrapping occurs.
推荐答案
仅靠CSS并不能完全实现您的要求。您可以执行的操作是设置每行要显示的最大项目数,然后计算传递给flexbox容器的最大宽度:
You can't achieve exactly what you're asking with CSS alone. What you can do it set the max number of items you want to show per row, and then calculate a max-width that you pass to your flexbox container:
:root{
--item-width: 100px;
--max-per-row: 4;
--max-width: calc( var(--max-per-row) * ( var(--item-width) + 1px) );
}
使用此代码,您可以将容器的宽度设置为所需的宽度,例如500px ,然后确保最大宽度为n *弹性框项目的宽度(边框加1),其中n是每行所需的项目数。只要确保flexbox宽度大于max-width。
With this code you can set your container's width to whatever you want, say 500px, and then make sure the max width is n * a flexbox item's width (plus 1 for border), where n is the number of items you want per row. Just make sure the flexbox width is greater than the max-width.
:root{
--item-width: 100px;
--max-per-row: 4;
--max-width: calc( var(--max-per-row) * ( var(--item-width) + 1px) );
}
body {
background: black;
}
.holder {
width: 650px;
background: gray;
margin-top: 50px;
}
.flexbox {
display: flex;
background: blue;
width: 500px;
max-width: var(--max-width);
flex-wrap: wrap;
}
.item {
width: var(--item-width);
height: 50px;
background: red;
border: 1px dotted white;
border-left: none;
}
.item.wide {
width: 200px;
}
<div class="holder">
<div class="flexbox">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
这篇关于为什么在包装元素后flexbox不能缩小以适合其尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!