Sophia Sophia - 6 months ago 19
HTML Question

Inline CSS Centering Not Working

I'm using this awesome site as a guide to inline CSS centering and am confused why most of it isn't working. The newer

flexbox
style only centers horizontally, not vertically:



<div style="display:flex;justify-content:center;align-items:center;">
<img src="https://66.media.tumblr.com/bac96f9db0dd31f09bad7f05db7e13c4/tumblr_o74utbKePP1u5sqevo1_500.gif"></img>
</div>





Whereas the legacy version for IE isn't working at all:



<div style="display:table;">
<div style="display:table-cell;vertical-align:middle;">
<div style="margin-left:auto;margin-right:auto;">
<img src="https://66.media.tumblr.com/bac96f9db0dd31f09bad7f05db7e13c4/tumblr_o74utbKePP1u5sqevo1_500.gif"></img>
</div>
</div>
</div>





Any ideas what the issue is? FYI, example image contains Orphan Black spoilers :)

Answer
  • with flexbox you need to set height

NOTE

<img> is a self-closing tag so you don't need to do </img> but instead />


body {
  margin: 0
}
div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh
}
<div>
  <img src="https://66.media.tumblr.com/bac96f9db0dd31f09bad7f05db7e13c4/tumblr_o74utbKePP1u5sqevo1_500.gif" />
</div>

  • regarding to CSS tables you need to set height in order to vertical-align:middle work, and add display:block, margin:auto to img to get it centered horizontally

body {
  margin: 0
}
div:first-of-type {
  display: table;
  width: 100vw;
  height: 100vh
}
div:last-of-type {
  display: table-cell;
  vertical-align: middle
}
img {
  display: block;
  margin: auto
}
<div>
  <div>
    <img src="https://66.media.tumblr.com/bac96f9db0dd31f09bad7f05db7e13c4/tumblr_o74utbKePP1u5sqevo1_500.gif" />
  </div>
</div>