2

Centring block elements

The basic technique: give a width and auto margin

You can horizontally centre a block element like a paragraph by giving it some width and using margin-left: auto together with margin-right: auto. Or, more simply, by using the shorthand margin: auto which sets all margins. The element itself, in relation to its own container, gets horizontally centred. The text within the child element is not itself thereby centred; for the inline content to be centred, the element generally needs the style of text-align: center.

A centred paragraph

Fig 1. <div><p style="width:300px; margin:auto;">A centred paragraph</p></div>

If the child is an img element set as display: block, then no width is strictly necessary because images have a native width and most browsers know it from information in the image file. But it is generally best to put an explicit width (as, say, an HTML attribute width="200" in the img element if only to help the page reserve space for it when loading. The img element, unlike a P or DIV, is shrink-to-fit; it has the width of the image. And, just by the way, the image itself is expand-to-fit the element; whatever is set in width attribute makes the image as wide!

CSS styling of width: auto acts to make the distance between the left and right of the img element equal with respect to the left and right edges of the parent container's content area.

Fig 2. <div><img style="display: block; margin: auto;" src="ruler.png" width="300" height="30" alt=""></div>

If both the element and inline content need centring, then the two different styles described on this and the last page need to be applied. For example:

Centred text in centred element

Fig 3. <div><p style="text-align: center; width: 300px; margin: auto; color: black; background: green;">Centred text in centred element</p></div>

In block centring, it is important to note that what gets centred is the element, not the content area of the element. This distinction between element centring and content centring constantly needs to be kept in mind in practice. 'text-align: centring' does a perfect job in centring inline content within the content area (the bit that is not padding, margin, borders) but element centring does not necessarily centre align the content area as you might hope for. As we see just above. But no need for exaggerated case, here is a real problem that some authors face: they want to centre a horizontal menu. How the menu is constructed determines how easy this is and what sort of centring is possible. Here are some of the different things some authors might want:

It will have to suffice for now to give some examples of how to achieve some of these requirements. First, the seemingly perfect centring of a horizontal list. There are a couple of ways to do this.

2