Spencer Avinger Spencer Avinger - 1 year ago 104
CSS Question

Using margin:auto to vertically-align a div

So I know we can center a div horizontally if we use

margin:0 auto;
. Should
margin:auto auto;
work how I think it should work? Centering it vertically as well?

Why doesn't
work either?

.black {
.message {
margin:auto auto;

<div class="black">
<div class="message">
This is a popup message.


Answer Source

You can't use:

vertical-align:middle because it's not applicable to block-level elements

margin-top:auto and margin-bottom:auto because their used values would compute as zero

margin-top:-50% because percentage-based margin values are calculated relative to the width of containing block

In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.

You can use:

A few workarounds like this which work for your scenario; the three elements have to be nested like so:

.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
.helper {
    #position: absolute;
    #top: 50%;
    display: table-cell;
    vertical-align: middle;
.content {
    #position: relative;
    #top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
<div class="container">
    <div class="helper">
        <div class="content">

JSFiddle works fine according to Browsershot.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download