html - Why is vertical-align: middle not working on my span or div?

ID : 10438

viewed : 28

Tags : htmlcsshtml

Top 5 Answer for html - Why is vertical-align: middle not working on my span or div?

vote vote

96

This seems to be the best way - some time has passed since my original post and this is what should be done now:

.main {   display: table;      /* optional css start */   height: 90px;   width: 90px;   /* optional css end */ }          .inner {   border: 1px solid #000000;   display: table-cell;   vertical-align: middle; }
<div class="main">   <div class="inner"> This </div> </div>

vote vote

86

Use flexbox and justify-content: center; to align elements horizontally in modern browsers:

.outer {   display: flex;   align-items: center;   justify-content: center; } 
<div class="outer">    <div class="inner"> Example </div> </div> 

Note: This might not work in old/dead browsers, like IE.

vote vote

77

Try this, works for me very well:

/* Internet Explorer 10 */ display:-ms-flexbox; -ms-flex-pack:center; -ms-flex-align:center;  /* Firefox */ display:-moz-box; -moz-box-pack:center; -moz-box-align:center;  /* Safari, Opera, and Chrome */ display:-webkit-box; -webkit-box-pack:center; -webkit-box-align:center;  /* W3C */ display:box; box-pack:center; box-align:center; 
vote vote

64

Setting the line-height to the same height as it's containing div will also work

DEMO http://jsfiddle.net/kevinPHPkevin/gZXWC/7/

.inner {     line-height:72px;     border: 1px solid #000000; } 
vote vote

53

In case you cannot rely on flexbox... Place .child into .parent's center. Works when pixel sizes are unknown (in other words, always) and no problems with IE9+ too.

.parent { position: relative; }    .child {      position: absolute;      top : 50%;      left: 50%;      -ms-transform: translate(-50%, -50%);      transform    : translate(-50%, -50%);      }
<div class="parent" style="background:lightyellow; padding:6em">     <div class="child" style="background:gold; padding:1em">&mdash;</div>   </div>

Top 3 video Explaining html - Why is vertical-align: middle not working on my span or div?

Related QUESTION?