html - 如何让 flex 元素扩展到每行最多 4 个元素的可用宽度?

标签 html css flexbox

我有一个 flexbox 容器,我希望容器内的元素使用尽可能多的宽度来填充行的整个宽度。但我也想让它每行只能有 4 个元素。因此,如果容器中有 1 个元素,我希望它采用 100% 的宽度,2 个元素各占 50%,等等,最多 4 个元素占 25%。我怎样才能做到这一点?

.container {
  width:800px;
  margin:0 auto;
  display:flex;
  flex-wrap:wrap;
}

.container > .item {
  min-width:25%;
  margin-left:10px;
}
  .container > .item:first-child, .container > .item:nth-child(5n) {
  margin-left:0;
  }
<h4>3 elements - should be 33% width each</h4>
<div class="container">
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50">
</div>
</div>

<h4>5 elements - should be 25% width each and wrap</h4>
<div class="container">
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50">
</div>
<div class="item"><img src="http://placehold.it/250x50">
</div>
<div class="item"><img src="http://placehold.it/250x50">
</div>
</div>

最佳答案

使用 flex-grow 属性消耗可用空间(当元素少于四个时),以及 flex-basis属性以确保每行最多四个元素。

.container {
  width: 800px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex: 1 0 20%;     /* fifth item will wrap because of left margin;
                        lots of leftover free space for margins */
  overflow: auto;    /* intrinsic size of 4 images is wider than container */
}

.item + .item {
  margin-left: 10px; /* applies only to items preceded by an item */
}

.item:nth-child(5n) {
  margin-left: 0;
}
<h4>3 elements - should be 33% width each</h4>
<div class="container">
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
</div>

<h4>5 elements - should be 25% width each and wrap</h4>
<div class="container">
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
  <div class="item"><img src="http://placehold.it/250x50"></div>
</div>

关于html - 如何让 flex 元素扩展到每行最多 4 个元素的可用宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61238531/

相关文章:

javascript - 在 IE 中使用 jQuery UI Selectmenu 插件时出错

html - 如何用 img 标签覆盖 div(就像 background-image 一样)?

jQuery CSS AddClass - RemoveClass 在 Internet Explorer 中移动 Div

css - HTML 选择元素

jquery - 使用 css 和 jquery 水平对齐绝对和静态元素

html - 在 HTML 和 CSS 中只获取 border-bottom

javascript - 单击按钮上的 Bootstrap 完整日历 View

html - 更改 flex 盒子的边距属性

html - css - <li> 中的意外换行符显示 :flex in Internet Explorer (and Edge)

html - Flex 框在悬停时移动