CSS Align

Web-pages do not just need to align the text content but other elements as well.

Although we do not have specific properties for this purpose, the vertical and horizontal alignment of the elements can be done in various ways.

Let us take a look at them one by one.

Center Align using Margin

To center aligns the elements horizontally, you can set the margin property as auto.

Once you specify and appropriate width as per the containing element, the remaining space will be equally divided between the left and right margins.

Run
In above div is aligned center but content inside div in not centered to make text centered we have to use
text-align:center

Run

Center Align Image

To center align an image, in addition to setting the margin to auto you can also set the display property to block so that it looks like a block element.

Run

Left and Right Align using position

You can align the elements to the left or right by setting the position to absolute and providing appropriate values to the left and right properties.

Run

Run

Left and Right Align using float

If you’re unsure of the values to be provided for the left and right properties, you can opt for the float property instead and directly provide the values left or right.

Make sure to keep the overflow property to be auto, in this case, to avoid the element to overflow from the container. This is called the clearfix hack.

Run

Vertically Center using padding

You can pad the element with appropriate values to make it vertically aligned.

Vertically Center using line-height

You can also set the line-height to a suitable value for the vertical alignment of the element.

Apart from padding and line-height, you can also use the position property by keeping it relative. Otherwise, you can use the transform property by giving the value as:

The transform property is mostly in the 2D-transformation which we will study in later chapters.

Categories CSS