CSS Align


CSS Layout - Horizontal & Vertical Align


Center elements
horizontally and vertically

To center a block element (like <div>) horizontally, you can simply use margin: auto; in your CSS code.

If you set the width of an element, it stops it from getting too wide and sticking to the sides of its box.

The element will use the given width, and the rest of the space will be evenly divided between the two margins.

Note: If the width property is not set or set to 100%, center alignment won't have any impact.


Center Align Text

To center the text within an element, apply the following style: `text-align: center;

Tip:For additional examples demonstrating how to position text, refer to the CSS Text section.


Center an Image

To position an image at the center, adjust the left and right margins to auto and convert it into a block element:


Left and Right Align - Using position

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

Note: Elements positioned absolutely are taken out of the regular flow, allowing them to overlap with other elements.


Left and Right Align - Using float

A different way to arrange elements is by employing the float property:


The clearfix Hack

Note:If an item is taller than the one containing it and is set to float, it may overflow beyond its container. To address this, you can apply the "clearfix hack" (see the example below).

Next, we can apply the clearfix hack to the enclosing element to resolve this issue.


Center Vertically - Using padding

There are several ways to vertically center an element in CSS. One straightforward approach involves utilizing top and bottom padding:

To center content both vertically and horizontally, employ padding and text-align: center.


Center Vertically - Using line-height

Another tip involves employing the line-height property with a value identical to the height property:


Center Vertically - Using position & transform

If you can't use padding and line-height , an alternative is to use positioning along with the transform property.


Center Vertically - Using Flexbox

You can use flexbox to center elements, but be aware that flexbox isn't supported in Internet Explorer 10 and earlier versions.