Home >Web Front-end >CSS Tutorial >How to Create a Responsive Grid of Squares with Centered Content?
In this Stack Overflow thread, a user inquires about creating a layout of responsive squares with vertically and horizontally aligned content.
The original solution proposed using the CSS display: flex property to create a flexible layout and the align-items: center and justify-content: center properties to center the content within each square. The responsive design was achieved using media queries.
<br>.container {<br> display: flex;<br> flex-direction: row;<br> flex-wrap: wrap;<br> justify-content: space-around;<br>}</p> <p>.square {<br> width: 100px;<br> height: 100px;<br> display: flex;<br> align-items: center;<br> justify-content: center;<br>}</p> <p>@media (max-width: 768px) {<br> .square {</p> <pre class="brush:php;toolbar:false">width: 50%;
}
}
With the evolution of CSS, several new properties have been introduced that simplify the implementation of a square grid layout:
<br>.container {<br> display: grid;<br> grid-template-columns: repeat(3, 1fr);<br> gap: 2%;<br>}</p> <p>.square {<br> aspect-ratio: 1/1;<br> display: flex;<br> align-items: center;<br> justify-content: center;<br> padding: 5%;<br> background-color: #1E1E1E;<br> color: #fff;<br>}</p> <p>.square img {<br> width: 100%;<br> height: 100%;<br> object-fit: contain;<br> object-position: center;<br>}</p> <p>.square.fullImg {<br> padding: 0;<br>}</p> <p>.square.fullImg img {<br> object-fit: cover;<br>}<br>
The final result creates a responsive grid layout with squares that can contain various types of content, including text, images, and lists, while maintaining alignment and aspect ratio.
The above is the detailed content of How to Create a Responsive Grid of Squares with Centered Content?. For more information, please follow other related articles on the PHP Chinese website!