Home >Web Front-end >CSS Tutorial >How Can I Create a Responsive Square Grid Using Flexbox and CSS?

How Can I Create a Responsive Square Grid Using Flexbox and CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 04:40:08497browse

How Can I Create a Responsive Square Grid Using Flexbox and CSS?

CSS Grid of Squares with Flexbox

Understanding Height and Width in Flexbox

Flexbox allows you to set the width of elements using the flex property. However, it does not control the height of elements. Flexbox will default to distributing the available height evenly among the elements.

Creating a Square Grid

To achieve a grid of squares, both the height and width of the squares must be equal. To do this:

  1. Set the Aspect Ratio: CSS aspect-ratio property can be used to define a fixed ratio between width and height. For squares, set the aspect ratio to 1 / 1.
.flex-item {
  aspect-ratio: 1 / 1;
}

Responsive Grid

To create a responsive grid that automatically adjusts to the viewport's width:

  1. Set flex to 1 0 auto: This allows the elements to grow to fit the width but prevents them from shrinking below their original width.
.flex-item {
  flex: 1 0 auto;
}
  1. Set a Container Width: Specify a fixed or percentage width for the parent container to limit the total width of the grid.
.flex-container {
  width: 100%;
  max-width: 800px;
}

Complete Code

<body>
  <div class="flex-container">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="flex-item">3</div>
    <div class="flex-item">4</div>
    <div class="flex-item">5</div>
    <div class="flex-item">6</div>
    <div class="flex-item">7</div>
  </div>
</body>
.flex-container {
  width: 100%;
  max-width: 800px;
  display: flex;
  justify-content: space-around;
  height: 50px;
  line-height: 30px;
}

.flex-item {
  background: tomato;
  margin: 5px;
  color: white;
  font-weight: bold;
  font-size: 1.5em;
  text-align: center;
  flex: 1 0 auto;
  aspect-ratio: 1 / 1;
}

The above is the detailed content of How Can I Create a Responsive Square Grid Using Flexbox and CSS?. 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