To align multiple images vertically, you can use CSS flexbox. In this method, you have to first put all the images inside a parent element let’s say a div and then make this element a flexbox by applying display: flex;
on it.
When you apply display: flex;
on an element, it starts behaving like a flexbox container and allows you to use any of the flexbox properties.
For example, you can use the align-items
property to align flex items vertically and the justify-content
property to align flex items horizontally.
Let’s say we have a div element with a class img-container
which contains three images inside of it:
<div class="img-container"> <img src="images/cat.jpg" width=170 height=170> <img src="images/cat.jpg" width=170 height=170> <img src="images/cat.jpg" width=170 height=170> </div>
Now, to vertically align these images inside of the div element, we will first make it a flex container by setting the display property to flex
.
Then, to vertically center these images inside of the div, we have to set the align-items property to center
. If you also want to center these images horizontally, you have to set the justify-content property to center
:
Example:
.img-container{ border: 2px solid red; height: 350px; display: flex; flex-wrap: wrap; align-items: center; /* Center Vertically */ justify-content: center; /* Center Horizontally */ column-gap: 10px; /* Set gap between images */ row-gap: 10px }
This is how the images will look like after applying the above styles: