How to create an image gallery with Grid and only two CSS classes
For my latest article I wanted to create a matrix of photos and the grid layout option of CSS came into the rescue. With only two CSS classes, one for the grid itself and one for the grid cells you can create a beautiful image gallery for your website.
We are also going to see how to apply the grid on Markdown code and how to change the way the grid is presented on mobile devices.
First we want to define the CSS code. Read further for explanation of what each property does.
.image-container {
display: grid;
grid-gap: 1em;
}
img {
width: 100%;
object-fit: cover;
}
.grid-2-1 {
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(1, 1fr);
}
.grid-2-2 {
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
}
- The
display:grid
property is obligatory so that the div works with the grid layout - The
grid-gap
property sets the padding between the grid elements, in our case the images - We then adapt the
img
element to fit our purposes as grid element. Theobject-fit
property adapts the image to be resized and fit the area of a grip cell. - Now we want to define different classes for different sized grids. We could also do that programmatically with JavaScript, but for the purposes of this article we do everything with CSS code.
- The
grid-template-columns
defines the number of columns our grid has. In the case of grid-2-1 we define 2 columns - The
grid-template-rows
defines the number of rows our grid has. In the case of grid-2-1 we define 1 row - The second parameter in both properties denotes the flexible length of the element within the grid container. More information about
flex
can be found here
- The
We now integrate the CSS class in our Markdown code by using this syntax: {: .image-container.grid-2-1 }
. We defined that our grid will have two columns and one row.
Finally we want all the images to be presented vertically when we view the website from our mobile device. For that we are going to use some more CSS and define a @media screen
property. We are going to override the value for the number of columns and set it to 1.
@media screen and (max-width: 767px) {
.grid-2-1, .grid-2-2 {
grid-template-columns: repeat(1, 1fr);
grid-template-rows: repeat(1, 1fr);
}
}
To vertically position the images inside a grid cell we can also use the align-items: self-end
property which would put the grid items on the bottom of each cell.