Home > Web Front-end > CSS Tutorial > How to Maintain Consistent Flex Item Widths Across Rows When Wrapping?

How to Maintain Consistent Flex Item Widths Across Rows When Wrapping?

Linda Hamilton
Release: 2024-11-24 19:46:12
Original
595 people have browsed it

How to Maintain Consistent Flex Item Widths Across Rows When Wrapping?

Ensuring Wrapped Flex Items Maintain Previous Row Widths

In a flex container, when flex items wrap, they tend to take up the maximum allowed space, leading to discrepant widths between items on different rows. To address this, we can employ the following CSS tricks:

Solution 1: Custom Mixin for Flex Items

Mixin:

@mixin flex-wrap-fix($flex-basis, $max-viewport-width: 2000px) {
  flex-grow: 1;
  flex-basis: $flex-basis;
  max-width: 100%;

  $multiplier: 1;
  $current-width: 0px;

  @while $current-width < $max-viewport-width {
    $current-width: $current-width + $flex-basis;
    $multiplier: $multiplier + 1;

    @media(min-width: $flex-basis * $multiplier) {
      max-width: percentage(1/$multiplier);
    }
  }
}
Copy after login

Usage:

Apply the mixin to the flex item:

.flex-item {
  @include flex-wrap-fix(100px)
}
Copy after login

Solution 2: Flex Container Mixin for Element Queries

Mixin:

@mixin flex-container-wrap-items($flex-basis, $max-expected-width: 2000px) {
  display: flex;
  flex-wrap: wrap;

  > * {
    max-width: 100%;
    flex-grow: 1;
    flex-basis: $flex-basis;
  }

  $multiplier: 1;
  $current-width: 0px;

  @while $current-width < $max-expected-width {
    $current-width: $current-width + $flex-basis;
    $multiplier: $multiplier + 1;

    &[min-width~="#{$flex-basis * $multiplier}"] > * {
      max-width: percentage(1/$multiplier);
    }
  }
}
Copy after login

Usage:

Apply the mixin to the flex container:

.flex-container {
  @include flex-container-wrap-items(100px)
}
Copy after login

The above is the detailed content of How to Maintain Consistent Flex Item Widths Across Rows When Wrapping?. For more information, please follow other related articles on the PHP Chinese website!

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