1

I'm trying to center an image which is contained in a div with display set to table. In it, I wish to display an image, which should be positioned in the center, both vertically and horizontally. I have achieved the horizontal position using margin:auto and setting it as display: table-cell, but it doesn't center it vertically. Any help would be great

.overlay { height: 50%; background: red;position: fixed;
top: 0;
left: 0;
height: 50%;
width: 100%;
display: table;}
.swipe {height: 80px;
display: table-cell;
margin: auto;}
<div style="height:300px">
<div class="overlay">
   <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />
user1038814
  • 9,337
  • 18
  • 65
  • 86

2 Answers2

7

I would recommend giving the .overlay <div> a flexbox layout instead of a table. Then you can center the image by simply applying three rules to the parent:

.overlay {
  display: flex;
  align-items: center;
  justify-content: center;
}

Note that you'll no longer need display: table-cell or margin: auto on .swipe.

This can be seen in the following example:

.overlay {
  height: 50%;
  background: red;
  position: fixed;
  top: 0;
  left: 0;
  height: 50%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.swipe {
  height: 80px;
}
<div style="height:300px">
  <div class="overlay">
    <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />
  </div>
</div>

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

Use padding at the top and bottom

.overlay { background: red; position: fixed;
top: 0;
left: 0;
padding: 5% 0 5% 0;
width: 100%;
display: table;}
.swipe {height: 80px;
display: table-cell;
margin: auto;}
<div style="height:300px">
<div class="overlay">
   <img class="swipe" src="https://d30y9cdsu7xlg0.cloudfront.net/png/255751-200.png" />
arjunsv3691
  • 791
  • 6
  • 19