Anonymouse
Anonymouse

Reputation: 25

Vertically center image in div

I have a div...

.posts-post-image {
  width: 100%;
  vertical-align: middle;
}

.posts-post-image-wrapper {
  max-height: 300px;
  overflow: hidden;
  width: 100%;
}
<div class="posts-post-image-wrapper">
  <img class="posts-post-image" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg">
</div>

The div's height is defined by max-height, so how can I vertically center the image?

All other solutions I have looked at don't cover max-height.

Upvotes: 0

Views: 58

Answers (1)

Cameron637
Cameron637

Reputation: 1719

If you make the wrapper a flexbox, you can use align-items to center the image like so:

.posts-post-image {
  width: 100%;
  vertical-align: middle;
}

.posts-post-image-wrapper {
  display: flex;
  align-items: center;
  max-height: 300px;
  overflow: hidden;
  width: 100%;
}
<div class="posts-post-image-wrapper">
  <img class="posts-post-image" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Lake_mapourika_NZ.jpeg">
</div>

Upvotes: 1

Related Questions