How to Vertically Align an Image inside a DIV with CSS

There are a few different ways to vertically align an image inside a parent div, which we learn about in this tutorial.

 

The Display Flex Method

The cleanest way to vertically align an image in the centre is with display: flex. The disadvantage of this is old browsers may not support it.

 

<div class="wrapper">
  <img src="cat.jpg" alt="cat">
</div>
.wrapper {
  height: 200px;
  width: 200px;
  border: 1px solid;
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  height: 100px;
}

 

With vertical-align: middle

Another way of aligning an image in the centre of an element is to apply a :before pseudo-class to the parent with, display: inline-block, height: 100% and vertical-align: middle. When vertical-align: middle is applied to the image it will vertically align to the centre of the parent div.

 

 

<div class="wrapper vert-align-objects">
  <img src="cat.jpg" alt="cat">
</div>
.wrapper {
  height: 200px;
  width: 200px;
  border: 1px solid;
}

.vert-align-objects::before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

img {
  height: 100px;
  vertical-align: middle;
}

 

To align the image in the centre on the horizontal axis, use text-align: center and a negative margin on the image if necessary.

 

.wrapper {
  height: 200px;
  width: 200px;
  border: 1px solid;
  text-align: center;
}

.vert-align-objects::before {
  content: '';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

img {
  height: 100px;
  vertical-align: middle;
  margin-left: -10px;
}

 

With Position Relative and Transform

Another clean solution is to use position: relative with top: 50% and transform on the vertical axis (Y).

 

<div class="wrapper">
  <img src="cat.jpg" alt="cat">
</div>

 

.wrapper {
  height: 200px;
  width: 200px;
  border: 1px solid;
}

img {
  height: 100px;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

 

Conclusion

All of the above methods will align an image in the centre of a parent element. If you need it to work with old browsers the vertical-align method is the way to go.

image