[英]Trying to fill up empty spaces using Flex box
有没有可能让这个黄色方块自然飘到空的灰色方块上等等? 每个 flex-item 代表一个组件,它们可以使用容器宽度的 50% 或 100%,但我在渲染它时只有这些信息。
我正在考虑只使用 flexbox,但我不知道是否可能。
.flex-container { display: flex; width: 200px; height: 240px; background: grey; flex-wrap: wrap; align-content: flex-start; } .flex-item { width: 100px; height: 100px; } .red { background: red; } .blue { background: blue; width: 200px; } .yellow { background: yellow; } .green { background: green; }
<div class="container"> <div class="flex-container"> <div class="flex-item red"></div> <div class="flex-item blue"></div> <div class="flex-item yellow"></div> <div class="flex-item green"></div> </div> </div>
使用 CSS-Grid 可以使用grid-auto-flow 属性: grid-auto-flow: row dense;
这将尽可能密集地放置物品并自动重新排序。
.flex-container { display: flex; }
.flex-container { display: flex; }
改为:更改.flex-container { display: grid; }
.flex-container { display: grid; }
使用CSS网格.flex-container { height: 240px; flex-wrap: wrap; align-content: flex-start; }
.flex-container { height: 240px; flex-wrap: wrap; align-content: flex-start; }
.flex-container { height: 240px; flex-wrap: wrap; align-content: flex-start; }
,以除去不必要的挠曲特性.flex-item { width: 100px; }
.flex-item { width: 100px; }
to: .flex-item { min-width: 100px; }
.flex-item { min-width: 100px; }
这允许元件是widerr然后100px的。.blue { width: 200px; }
.blue { width: 200px; }
to: .blue { grid-column: span 2; }
.blue { grid-column: span 2; }
有该元素的宽度的两倍。 .flex-container { display: grid; width: 200px; background: grey; grid-auto-flow: row dense; } .flex-item { min-width: 100px; height: 100px; } .red { background: red; } .blue { background: blue; grid-column: span 2; } .yellow { background: yellow; } .green { background: green; }
<div class="container"> <div class="flex-container"> <div class="flex-item red"></div> <div class="flex-item blue"></div> <div class="flex-item yellow"></div> <div class="flex-item green"></div> </div> </div>
我确实看到有一些关于此的评论,@Tacoshy 认为网格是更好的解决方案是正确的。 但是 - 这里是如何使用order
和flex
来做到这一点,因为 OP 指定了“使用 flexbox”:
(出于显而易见的原因,我还将灰色div
的高度从 240 更改为 300。)
.flex-container { display: flex; width: 200px; height: 300px; background: grey; flex-wrap: wrap; align-content: flex-start; } .flex-item { width: 100px; height: 100px; } .red { background: red; order: 0; } .blue { background: blue; width: 200px; order: 2 } .yellow { background: yellow; order: 1; } .green { background: green; order: 3 }
<div class="container"> <div class="flex-container"> <div class="flex-item red"></div> <div class="flex-item blue"></div> <div class="flex-item yellow"></div> <div class="flex-item green"></div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.