Dead Centre Revisited

The demise of IE6 and 7 mean that there are now many more powerful ways to achieve many effects using CSS. When IE6 was the latest version of Internet Explorer that was available you needed to use at least two divs in order to be able to get something to display centred both horizontally and vertically inside of your page or part of your page (or at least I never saw any solution offered that used less than three divs other than the two div solution I worked out). As two divs were required for IE6 that meant that two divs were going to be there for other browsers as well and so a solution involving the two divs using display:table and display:table-cell seemed reasonable.

More recently other solutions to this centring problem have been produced. The simplest involves modifying the way the CSS for the element is defined so that the auto margin that is used to centre things horizontally will also work to centre it vertically. We start by defining an element as position:absolute (which means you need to apply position:relative to the element within the page you want it centred in or it will be centred in the viewport instead). The next step is to define the offsets from each and every side of the container that we want this overlayed absolute object to occupy. This means specifying a distance of zero for each of the left, top, right, and bottom sides. With these in place we can now specify margin:auto and all four margins will be determined automatically taking the size of the element into account. These definitions basically make the size of the object plus its margins equal to the size of the container.

As with using margin:0 auto to do horizontal centring where a width is needed, this absolute centring using margin:auto requires both a width and a height. Each margin will then be auto determined to be exactly half of the difference between the size of the element and the size of its container and the element will be placed in the absolute centre.

.ctr {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background: #ccc;


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow