Flexbox layout: 4 elements per row
When using Flexbox to dynamically resize 8 elements on the page, how to force them to be divided into for two rows (4 per row)?
Given the following code snippet:
<div class="parent-wrapper"> <div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> </div>
.parent-wrapper { height: 100%; width: 100%; border: 1px solid black; } .parent { display: flex; font-size: 0; flex-wrap: wrap; margin: -10px 0 0 -10px; } .child { display: inline-block; background: blue; margin: 10px 0 0 10px; flex-grow: 1; height: 100px; }
Solution:
The problem is with flex-wrap: wrap on the flex container , which allows elements to wrap. However, flex-grow: 1 allows unlimited growth on elements, causing them to fail to wrap when they run out of space.
The solution is to define a width for the element, forcing it to wrap:
.parent { display: flex; flex-wrap: wrap; } .child { flex: 1 0 21%; /* 展开说明如下 */ margin: 5px; height: 100px; background-color: blue; }
The first value of the flex property (1 in our example) distributes the space evenly to all element, the second value (which is 0) sets the minimum width to 0, and the third value (which is 21%) defines the maximum width of the element to 21% of the available width. By setting it up like this, the elements will wrap before reaching the maximum width, creating a layout of 4 elements per row.
The above is the detailed content of How to Force Two Rows of Four Elements Each Using Flexbox When Dynamically Resizing Eight Elements?. For more information, please follow other related articles on the PHP Chinese website!