How to center a fixed/absolute div using css – browser hack

Today i learned about centering a fixed/absolute positioned div using simple browser hack. This is useful when you want to display a loading callback during ajax calls. It works in my Firefox 3.6.27, IE9, Opera 11.61, Chrome 18.0, & Safari.

Loading...
#busy-indicator {
    background: #FFFFFF;
    border: 3px solid #B9D4F2;
    color: #B9D4F2; 
    height: 40px;
    left: 50%;
    margin-left: -30px;
    margin-top: -30px;
    padding: 5px;
    position: fixed;
    text-align: center;
    top: 50%;
    width: 60px;
    z-index: 200;
}

This is how it works,
center vertically:
set top: 50% and margin-top: -height/2

center horizontally:
set left: 50% and margin-left: -width/2
or
set right: 50% and margin-right: -width/2

Leave a Comment