1

Here's my HTML:

<div class="overlay">
  <div id="loading">
    <img src="styles/images/30.gif">
  </div>
</div>

I want to make it centered vertically and horizontally.
The image is only centered horizontally, as shown on the screenshot below:

enter image description here
My CSS looks like this:

.overlay {
   background: #e9e9e9;
   display: none;
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   opacity: .5;
}

#loading {
   text-align: center;
}

#loading img {
   display: table-cell;
   margin: 0 auto;
}

What should I do to make it centered vertically? Thanks in advance.

undefined
  • 1,019
  • 12
  • 24
kurniawan26
  • 793
  • 4
  • 16
  • 35

2 Answers2

2

the parent (#loading) height is the height of the child element (img). because vertical alignment doesn't make sense. set the parent of the greater height, then the inner element can be centered vertically by any available means.

* {
  padding: 0;
  margin: 0;
}

.overlay {
  background: #e9e9e9;
  opacity: 0.5;
}

#loading {
  display: flex;
  height: 100vh;
}

#loading img {
  margin: auto;
}
<div class="overlay">
  <div id="loading">
    <img src="http://placehold.it/160x120">
  </div>
</div>
Andrei Fedorov
  • 3,689
  • 2
  • 13
  • 25
0

There are a few ways to achieve vertical alignment, many of which get complicated.

One of the simplest fixes involves setting your element to absolute positioning and margins to auto, while defining both the top and the bottom at 0.

#loading {
    position: relative;
}
#loading img {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}

Link to jsfiddle.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Orun
  • 4,383
  • 3
  • 26
  • 44
  • Lol @ your superfluous edit [Nisse Engström](http://stackoverflow.com/users/3478852/nisse-engstr%c3%b6m). I hope you don't always impose your syntactical preferences on others. – Orun Apr 29 '17 at 14:56
  • It was suggested by someone else and went through the Suggested Edits review queue. The edit improves readability (in my opinion) and is in the same style as the code in the question, so it makes some sense at least. If you feel strongly about it, you can always unroll the changes from the [revision history](http://stackoverflow.com/posts/43692042/revisions). – Nisse Engström Apr 29 '17 at 21:45