Home >Web Front-end >CSS Tutorial >How Can I Create a Responsive Square Grid Using Flexbox and CSS?
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:
.flex-item { aspect-ratio: 1 / 1; }
Responsive Grid
To create a responsive grid that automatically adjusts to the viewport's width:
.flex-item { flex: 1 0 auto; }
.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!