CSS Layout - Horizontal & Vertical Align

Center Align Elements

To horizontally center a block element (like <div>), use margin: auto;

Setting the width of the element will prevent it from stretching out to the edges of its container.

The element will then take up the specified width, and the remaining space will be split equally between the two margins:

Example -

Center Align Text

To just center the text inside an element, use text-align: center;

Example -

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Example -

Left and Right Align - Using position

One method for aligning elements is to use position: absolute;:

Example -

Left and Right Align - Using float

Another method for aligning elements is to use the float property:

Example -

Center Vertically - Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:

Example -

Center Vertically - Using line-height

Another trick is to use the line-height property with a value that is equal to the height property.

Example -