Home > Web Front-end > CSS Tutorial > How to Force Two Rows of Four Elements Each Using Flexbox When Dynamically Resizing Eight Elements?

How to Force Two Rows of Four Elements Each Using Flexbox When Dynamically Resizing Eight Elements?

Susan Sarandon
Release: 2024-12-29 08:07:10
Original
295 people have browsed it

How to Force Two Rows of Four Elements Each Using Flexbox When Dynamically Resizing Eight Elements?

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>
Copy after login
.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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template