DEV Community

Cover image for A Complete Guide to Centering in CSS (Horizontally, Vertically)
Muhammet Fatih Gul
Muhammet Fatih Gul

Posted on

A Complete Guide to Centering in CSS (Horizontally, Vertically)

Horizontal Inline (texts and links etc.)

.div{
    text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Horizontal Block(divs and lists etc.)

.div{
    margin: 0 auto;
}
Enter fullscreen mode Exit fullscreen mode

Vertical Inline (texts and links etc.)
If you want to vertically align inline elements, you have two options
First one is giving equal padding-top and padding-bottom.

.text{
    padding-top: 25px;
    padding-bottom: 25px;
}
Enter fullscreen mode Exit fullscreen mode

The second one is changing line-height equal to box height. To do that, make sure you use "white-space" is "nowrap". So, it's not going to wrap. If you want to make multiple lines and vertically align. You can still set padding-top and bottom equally.

.text{
    height: 150px;
    line-height: 150px;
    white-space: nowrap;
}
Enter fullscreen mode Exit fullscreen mode

Vertical Block (divs and tables etc.)
If you know the height of the element:

.parent{
   position: relative;
}
.child{
   position: absolute;
   top: 50%;
   height: 100px; /*This height is equal to parent's height */
   margin-top: -50px;
}
Enter fullscreen mode Exit fullscreen mode

If you don't know the heights of the elements.

.parent{
   position: relative;
}
.child{
   position: absolute;
   top: 50%;
   transform: translateY(-50%);
}
Enter fullscreen mode Exit fullscreen mode

A better way
Don't hesitate to use flexbox and grid system. I'm using them almost for everything. Even for the simplest things. It's not going to make your website load slower. Best way to center everything and easy to handle.

Centering Horizontally

.parent{
   display: flex;
   justify-content: center; 
}
Enter fullscreen mode Exit fullscreen mode

Centering Vertically

.parent{
   display: flex;
   align-items: center; 
}
Enter fullscreen mode Exit fullscreen mode

Centering Horizontally and Vertically

.parent{
   display: flex;
   justify-content: center;
   align-items: center; 
}
Enter fullscreen mode Exit fullscreen mode

Using grid to center both way

.parent{
   height: 500px;
   display: grid;
}
span{
   margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)