DEV Community

Anderson Vilela
Anderson Vilela

Posted on

5 Different Ways to Center a Div

Horizontal Centering

Horizontal centering is useful when we want to center a div horizontally on the page. To do this, we can use the following CSS code:

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


Enter fullscreen mode Exit fullscreen mode

This code centers the div horizontally by setting an automatic left and right margin and setting the width of the div to 50% of the parent container.

Vertical Centering

Vertical centering is a bit more complicated, but can be achieved with the following CSS code:

.container {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;
}

.content {
   /* Style the div to be centered */
}

Enter fullscreen mode Exit fullscreen mode

In this example, we create a parent container with display flex, and set the justify-content property to center and align-items to center. We then set the height of the container to 100vh. Next, we define styles for the div we want to center.

Horizontal and Vertical Centering

To center a div both horizontally and vertically, we can combine the above techniques. The following CSS code can be used:

.container {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;
}

.content {
   margin: self;
}

Enter fullscreen mode Exit fullscreen mode

In this example, we use the same vertical centering technique as the previous technique, but we add an automatic margin to center the div horizontally.

See more at: https://tablognews.netlify.app/posts/post/5-formas-diferentes-de-centralizar-uma-div

Top comments (0)