Centering a fixed-size element using CSS

November 24, 2011 by David Corvoysier

This blog post summarizes several options you have to vertically center a div using CSS.
The option 4 applies in particular to elements whose height is known: in a nutshell, you ask the browser to stick an element of a specified height to the borders of a bigger containing box, which leads to an automatic adjustment of the container inner margins.
.centered {
position: absolute;
margin: auto;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}

#red {
background-color: red;
}

#blue {
background-color: blue;
width:25%;
height: 25%;
}

<div id="red" class="centered"></div>
<div id="blue" class="centered"></div>

As you can see, the red div stretches to stick to the containing div borders, but the blue div keeps its dimensions and is centered.


No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment