gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:57:32 26 4
gpt4 key购买 nike

我有一个 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/

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