How to use Flex box In CSS
In this approach we will utilize Media queries create a Responsive Image Grid. Initially we set the Flexbox properties to display: flex and flex-wrap: wrap to the container for enabling the items to wrap onto multiple lines as needed. For each image item we set flex: 0 1 calc(33.33% – 20px) which displays 3 images in one row. For screens with a maximum width of 768px, each item’s flex basis is changed to calc(50% – 20px) to have two items per row and for screens with a maximum width of 480px, each item spans the full container width (calc(100% – 20px)) to keep a single item per row.
Example: Below example uses Media queries to create a Responsive Image Grid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Responsive Image Grid</title>
<style>
.image-grid {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.image-item {
flex: 0 1 calc(33.33% - 20px);
margin-bottom: 20px;
}
.image-item img {
width: 100%;
height: auto;
}
@media screen and (max-width: 768px) {
.image-item {
flex: 0 1 calc(50% - 20px);
}
}
@media screen and (max-width: 480px) {
.image-item {
flex: 0 1 calc(100% - 20px);
}
}
</style>
</head>
<body>
<h3>Creating responsive image grid using Media quries</h3>
<div class="image-grid">
<div class="image-item"><img
src=
"https://media.w3wiki.org/wp-content/uploads/20240522105246/images-(1).png"
alt="GFG logo">
</div>
<div class="image-item"><img
src=
"https://media.w3wiki.org/wp-content/uploads/20240522105246/images-(1).png"
alt="GFG logo">
</div>
<div class="image-item"><img
src=
"https://media.w3wiki.org/wp-content/uploads/20240522105246/images-(1).png"
alt="GFG logo">
</div>
<div class="image-item"><img
src=
"https://media.w3wiki.org/wp-content/uploads/20240522105246/images-(1).png"
alt="GFG logo">
</div>
<div class="image-item"><img
src=
"https://media.w3wiki.org/wp-content/uploads/20240522105246/images-(1).png"
alt="GFG logo">
</div>
<div class="image-item"><img
src=
"https://media.w3wiki.org/wp-content/uploads/20240522105246/images-(1).png"
alt="GFG logo">
</div>
</div>
</body>
</html>
Output:
How to Create a Responsive Image Grid using CSS?
A responsive image grid is a layout technique used to display images in a grid-like structure that adjusts dynamically based on the screen size to ensure that the grid looks good and functions well across various devices and screen resolutions.
Below are the approaches to creat a responsive image grid using CSS:
Table of Content
- Using CSS Grid
- Using Flex box