Login | Contact Us | Site Map | Resources

The Inner Workings of CSS

Home > CSS Tutorial > CSS Horizontal Alignment

CSS Alignment

HTML elements can be horizontally aligned to the left (which is the default), right or center of their containing elements. One way to do this is to set the element's margin.

Setting the left and right margins to auto will center an element by equally splitting the available margin. Aligning an element to the left or the right requires one margin to be set to zero and the other margin to be set to auto. (Elements with a width of 100% cannot be aligned.)

This Is A Paragraph

If you clicked on the buttons above, you will notice that for the sake of our example, each button moves the little blue-bordered paragraph around. The text on each button describes the settings that are applied to the paragraph in order to place it in each position.

Now let's look at a practical example by centering a little blue-bordered paragraph.

  <p style="border: 1px solid #005A98; margin-left: auto; margin-right: auto;
width: 400px;">Why does a flamingo lift up one leg?<br />
Because if he lifted up both legs he would fall over!<p>

The result is:

Why does a flamingo lift up one leg?
Because if he lifted up both legs he would fall over!