In this article, we'll discuss how to create a grid layout with responsive squares using CSS.
For CSS Grid, we can use a combination of grid-template-columns and the padding-bottom trick to create responsive squares. The padding-bottom trick assigns a percentage value to the square's padding, effectively setting its aspect ratio to 1:1.
.square-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); } .square { padding-bottom: 100%; }
With Flexbox, we can use a similar padding-bottom technique to create responsive squares. We can set the flex items to have equal aspect ratios by assigning a percentage value to their padding.
.square-container { display: flex; flex-wrap: wrap; } .square { flex-basis: calc(33.333% - 10px); margin: 5px; padding-bottom: 100%; }
Note that both approaches require the use of pseudo-elements or extra wrappers to ensure that the percent padding is applied to the square itself, not its flex or grid item.
To collapse the grid layout to a single column on smaller screens, we can use media queries.
@media (max-width: 768px) { .square-container { grid-template-columns: 100%; flex-direction: column; } }
By combining these techniques, we can create a grid layout with responsive squares that maintains a consistent aspect ratio across different screen sizes and device orientations.
The above is the detailed content of How to Build Responsive Squares in a Grid Layout Using CSS Grid and Flexbox?. For more information, please follow other related articles on the PHP Chinese website!