How to horizontally center elements (div) in Css

How to horizontally center elements (div) in Css

In this tutorial, we are going to learn about three different ways to horizontally center the elements in css.

1. Horizontally centering using flexbox

To horizontally center a elements like (div) we need to add display:flex and justify-content:center to the element css class.

Example:

<div class="center">
   <h1>I'm Horizontally center</h1>
</div>
.center{
   display:flex;
   justify-content:center;
}

horizontal-center-using-flex-box

2. Horizontally centering using margins

This example shows you how to horizontally center elements using margins and width.

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

In the above code, we have added width:50% and margin:0 auto so that the element equally splits the available space between the left and right margins.

3. Horizontally centering using transform

This example shows you how to horizontally center elements using position and transform properties.

.center{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
  1. Here first we added position:absolute, so that element comes out from the normal document flow.
  2. second we added left:50%, so that element moves forward 50% towards x-axis.
  3. Third, we added transform:translateX(-50%), so that element comes backward 50% and align it to center.