Home >Web Front-end >CSS Tutorial >How to Create a Responsive Grid of Squares with Centered Content?

How to Create a Responsive Grid of Squares with Centered Content?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 19:10:10380browse

How to Create a Responsive Grid of Squares with Centered Content?

Grid of Responsive Squares

In this Stack Overflow thread, a user inquires about creating a layout of responsive squares with vertically and horizontally aligned content.

Original Solution (2018)

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%;

}
}

Updated Solution (2022)

With the evolution of CSS, several new properties have been introduced that simplify the implementation of a square grid layout:

  • grid: Defines a grid layout for the container.
  • aspect-ratio: Specifies the aspect ratio of each grid item, ensuring it remains square.
  • object-fit: Controls how images are displayed within the squares, allowing for centering and image fitting behavior.

<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!

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