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

How to Create a Responsive Grid of Squares Using CSS?

Barbara Streisand
Release: 2024-12-20 02:43:20
Original
736 people have browsed it

How to Create a Responsive Grid of Squares Using CSS?

Creating a Responsive Grid of Squares

Introduction:
Creating a layout featuring responsive squares can often be a challenging task. However, with the help of CSS techniques, achieving this effect is possible.

Responsive Squares Layout:
The provided example demonstrates a grid of squares with vertically and horizontally aligned content. To implement this layout, we'll utilize the "grid" and "aspect-ratio" properties.

CSS Implementation:
The CSS code below establishes the grid and sets the aspect ratio of each square to maintain its square shape:

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2%;
}

.square {
  aspect-ratio: 1 / 1;
}
Copy after login

Content Alignment:
To align the content within each square, we'll employ the "flex" property and "align-items" property:

.square {
  display: flex;
  align-items: center;
}
Copy after login

Flexible Content Handling:
The squares can accommodate various content types, including text, images, and lists. To ensure the content remains centered, we'll apply appropriate padding and ensure images are contained within the squares:

.square {
  padding: 5%;
}

.square img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: center;
}
Copy after login

Full-Width Images:
For squares displaying full-width images, we'll remove the padding and adjust the object-fit property to cover the square completely:

.square.fullImg {
  padding: 0;
}

.square.fullImg img {
  object-fit: cover;
}
Copy after login

Dynamic Sizing:
By defining the "grid-template-columns" property as "repeat(3, 1fr)", the squares adjust their width dynamically based on the available space, maintaining a responsive layout on different screen sizes.

The above is the detailed content of How to Create a Responsive Grid of Squares Using CSS?. 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