Home > Web Front-end > CSS Tutorial > How to Build Responsive Squares in a Grid Layout Using CSS Grid and Flexbox?

How to Build Responsive Squares in a Grid Layout Using CSS Grid and Flexbox?

Susan Sarandon
Release: 2024-11-26 06:21:09
Original
975 people have browsed it

How to Build Responsive Squares in a Grid Layout Using CSS Grid and Flexbox?

How to Create a Grid Layout with Responsive Squares

In this article, we'll discuss how to create a grid layout with responsive squares using CSS.

CSS Grid Approach

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%;
}
Copy after login

Flexbox Approach

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%;
}
Copy after login

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.

Using Media Queries for Responsiveness

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;
    }
}
Copy after login

Conclusion

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!

source:php.cn
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