Home >Web Front-end >CSS Tutorial >How to Create a Responsive Grid Layout of Equal-Sized Squares Using CSS Grid or Flexbox?

How to Create a Responsive Grid Layout of Equal-Sized Squares Using CSS Grid or Flexbox?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 15:04:09513browse

How to Create a Responsive Grid Layout of Equal-Sized Squares Using CSS Grid or Flexbox?

Responsive Grid Layout with Equal-Sized Squares

Problem:

Devise a responsive grid layout consisting of equally sized squares, with adaptable gutter spacing. Consider both CSS Grid and Flexbox approaches.

Solution:

CSS Grid with Padding Trick:

Utilize the "padding-bottom" trick to force square proportions. Add a pseudo-element with a percentage padding-bottom corresponding to the desired square aspect ratio (e.g., 100%). This simulates a fixed height for the square container.

.square {
  position: relative;
  ...
  padding-bottom: 100%;
}

.square::before {
  content: '';
  display: block;
  padding-top: 100%;
}

Flexbox with Absolute Positioning:

Employ a Flexbox layout with a pseudo-element. Set the height of the pseudo-element to the square aspect ratio (e.g., 100%), and absolutely position the content within the square container.

.square {
  position: relative;
  ...
  flex-grow: 0;
}

.square::before {
  content: '';
  display: block;
  height: 100%;
}

.square .content {
  position: absolute;
  top: 0; left: 0;
  height: 100%;
  width: 100%;
}

Gutter Spacing:

For both approaches, apply margin or padding to the square elements to create gutters.

Note: Ensure that content is absolutely positioned within the squares to maintain aspect ratio.

The above is the detailed content of How to Create a Responsive Grid Layout of Equal-Sized Squares Using CSS Grid or Flexbox?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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