The CSS way to align things

There are two ways to align things in CSS and these depend on what we want to align: text or an actual element.

Aligning text

To align text, we must first make sure it isn't inside an inline element. Inline elements cannot be aligned on a page, nor have their content aligned, as they "shrink-wrap" to fit their content, whereas block elements do not behave in the same way.

text-align:[center][left][right][justified];

Example

Suppose we want to centre align some text inside a paragraph:

p { text-align:center; }

To align a block element on a page

Centre Align

Place this code on the element you want to centre align, making sure to remove any floats that may have been applied to the element. A float:left or float:right will cause the style decleration to break.

margin:0 auto;

Right Align

To right align an element on a page we give it a float:right, which pushes it up against the right-hand side of its containing element.

float:right;

Note that you don't need to align a block element left as that is it's default position.

Aligning inline elements

I know I said we couldn't align inline elements, but that isn't strictly true. If we were to convert an inline element to a block element, it would then behave exactly how a block element behaves. This comes in useful with labels in forms, say for instance, where you want your labels to all be the same width. To do this we convert the labels into block elements. The below examples make use of the Type and Class Selectors.

The Class Selector

When this class is applied to a label, it will be converted into a block element.

.formEl { display:block; }

The Type Selector

We don't do anything with this. It automatically styles all labels on our site.

label { display:block; }

We can now manipulate the text inside our label:

label { display:block; width:100px; height:22px; background-color:#EBEBEB; border-left:3px solid black; text-indent:3px; float:left; }

Result

I have formatted the label, given it a float:left to float it next to the input element. As it is now a block element it needs to be floated if it is to be placed next to another block element. I have also given it a width and height. Without a width it would expand to fill the parent container.

Got any questions or comments? Feel free to mail me @ helen@alternategateways.com.

Back to resources.