Creating a Gallery with Grid
Let's open the CSS tab and define the following classes!
.gallery {
display: grid;
max-width: 1000px;
margin: auto;
grid-template-columns: repeat(2, 1fr);
grid-auto-rows: minmax(280px, auto);
grid-gap: 14px;
}
This code defines a CSS class called "gallery" as follows:
-
display: grid;
: Sets the element with the "gallery" class to be displayed as a grid -
max-width: 1000px;
: Limits the maximum width of the grid to 1000 pixels -
margin: auto;
: Centers the grid on the page -
grid-template-columns: repeat(2, 1fr);
: Creates two columns in the grid container, each column having equal width -
grid-auto-rows: minmax(280px, auto);
: Sets the height of the rows in the grid container. "minmax(280px, auto)" means that the row's height will be at least 280px but can grow automatically. Thus, no matter how small the height of the grid items, they will be at least 280px tall, and if the height exceeds 280px, it adjusts automatically. -
grid-gap: 14px;
: Sets the space between grid items to 14px.
Let's add 4 images into the grid container as follows.
<div class="gallery">
<img
src="https://images.pexels.com/photos/376464/pexels-photo-376464.jpeg"
width="100%"
height="100%"
alt="Item 1"
/>
<img
src="https://images.pexels.com/photos/70497/pexels-photo-70497.jpeg"
width="100%"
height="100%"
alt="Item 2"
/>
<img
src="https://images.pexels.com/photos/1099680/pexels-photo-1099680.jpeg"
width="100%"
height="100%"
alt="Item 3"
/>
<img
src="https://images.pexels.com/photos/958545/pexels-photo-958545.jpeg"
width="100%"
height="100%"
alt="Item 4"
/>
</div>

As set in the "gallery" class with grid-template-columns: repeat(2, 1fr);
, it creates two columns and the minimum height of each row is set to 280px.
Now, if you change "grid-template-columns: repeat(2, 1fr);"
from repeat(2, 1fr)
to repeat(4, 1fr)
, the number of columns increases from 2 to 4!
Next, if you change minmax(280px, auto)
to minmax(140px, auto)
in "grid-auto-rows: minmax(280px, auto);", the height of the grid items is reduced to 140px, which is half of 280px.
Finally, you can see the effect of changing grid-gap: 14px;
to 28px
, which increases the gap between the grid items.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.