CSS Alignment

In CSS we can align the html elements in different ways.

Center Alignment Using the margin Property

To align a block level element horizontally in the center, give value of the margin for that element auto.

Example

div {
    width: 50%;
    margin: 0 auto;
}

Text Alignment

Use the text-align property to align the text to align the text inside an element.

Example

h1 {
    text-align: center;
}
p {
    text-align: left;
}

Center Vertically – Using padding

By defining the top and bottom padding of an element, we can also vertically align its contents in the center.

Example

.center {
  padding: 70px 0;
  border: 3px solid green;
}

Left and Right Alignment Using the float Property

CSS float can float image by right or left side and show content around it. In addition to Image, Block Level Elements of HTML can also be float.

Example

div {
    width: 200px;
    float: left;
}