6

Using absolute positioning to centre.

Using absolute positioning, one can centre a block by positioning it half way and then, using its known width, moving its left margin negatively by half its width. Similar can be done with height to achieve a centring that many people hanker for. But this known technique is not always so easy to apply when fitted into a real page that has lots of other demands.

The examples below should explain the idea involved. In the captions, I leave out the mark-up for the parent container (the box with the grid). But it is important to note one particular feature of the parent CSS, namely its position: relative; instruction. This is to force the parent to make the child's absolute coordinates relate to itself rather than, in effect, the viewport.

First let us get the top left point of the crimson child element centred:

Fig 1. <div style="position:absolute; left:50%; top:50%; width:300px; height:100px; background-color:#cfc;"></div>

And now let's add negative margins to pull the left edge of the crimson box, by half the amount of the crimson box's width and also do the corresponding task with the height:

Fig 2. <div style="position:absolute; left:50%; width:300px; height:100px; margin:-150px auto auto -50px; background-color:#cfc;"></div>

You can see a purer example of this centring where an element is centred in the body as parent. No need for relative positioning of the parent in this case.

Next we go into centring background images within an element, something that some people like to do.

6