How to Center Vertically and Horizontally in CSS

When it comes to designing web pages, centering elements can be a tricky task.

However, with CSS, it’s possible to center elements both vertically and horizontally on a web page.

In this CSS tutorial, we’ll take a look at how to center elements both vertically and horizontally using CSS.


Vertical Centering

There are several ways to center elements vertically in CSS, but the most common method is to use the transform property with the translateY value.

This method works by setting the element’s position to absolute and then using the transform property to move the element up or down by a certain amount.

The following code shows an example of how to center an element vertically on a page:

.parent {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

In this example, the parent class is used to create a container element that the child class can be placed within.

The child class is then given a position of absolute and the top property is set to 50%.

This positions the top of the element at the halfway point of the parent container.

The transform property is then used with the translateY value set to -50%.

This moves the element up by half of its own height, effectively centering it vertically within the parent container.

Horizontal Centering

Centering elements horizontally is a bit easier than vertical centering.

The most common method is to use the margin property.

By setting the left and right margins to auto, the element will be centered horizontally within its parent container.

The following code shows an example of how to center an element horizontally on a page:

.parent {
    width: 100%;
}

.child {
    width: 50%;
    margin: 0 auto;
}

In this example, the parent class is given a width of 100% and the child class is given a width of 50%.

The margin property is then set to 0 auto, which sets the left and right margins to auto.

This causes the element to be centered horizontally within the parent container.


Conclusion

Centering elements both vertically and horizontally in CSS can be a tricky task, but by using the methods outlined in this tutorial, it’s possible to achieve the desired result.

The key to successful centering is to use the transform and margin properties in combination with the position property.

With a bit of practice, you’ll be able to center elements with ease.

Note: These methods work well when the parent container has a defined width and height, if the parent container is not defined, other methods needs to be used.