Why doesn't flexbox shrink to fit after wrapping elements? [duplicate]

江枫思渺然 提交于 2020-01-11 09:55:08

问题


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.

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.

Here is a link to a codepen demonstrating the issue:

https://codepen.io/heroes-coding/pen/rNaGYmo

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;
}

I'd like to have the flexbox still wrap at 500px but shrink to fit the content after the wrapping occurs.


回答1:


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)  );
}

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>


来源:https://stackoverflow.com/questions/59546818/why-doesnt-flexbox-shrink-to-fit-after-wrapping-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!