DEV Community

Akash Varma
Akash Varma

Posted on

Different ways to centre an element in css

Hello DEVelopers!!

We will see how to center an element in css using different ways.

For all the examples, I will be using below html as common one.

<div class="parent">
   <div class="child"></div>
</div>

Using Position

.parent {
   position: relative;
}
.child { 
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

Using margin in position

margin: auto works only for horizontal alignment.
But we can make it to work in both directions using below code.

.parent {
   position: relative;
}
.child { 
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
//by giving top,left,right,bottom values as 0 now child's width and height is exact to parent.
   width: 800px; //assuming random width
   height: 200px; //assuming random height
   margin: auto; //margin auto works for both vertical and horizontal alignments
}

Using Flex

.parent {
   display: flex;
   align-items: center;
   justify-content: center;
}

Using Grid

.parent {
    display: grid;
    justify-content: center;
    align-items: center;
}

Using Table

.parent {
   display: table;
   width: 100px;
   height: 100px;
}
.child {
   display: table-cell;
   vertical-align: middle;
   width: 50px;
   height: 50px;
   text-align: center;
}

Using text-align to center horizontally

.parent {
   display: block;
   text-align: center;
} 
.child {
   display: inline-block; //key point
}

Using line-height to center vertically

It works fine if there is only one line.

.parent {
   height: 200px;
}
.child {
   line-height: 200px; //same value of parent height
}

Using margin as auto to center horizontally

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

Top comments (6)

Collapse
 
svaani profile image
Vani Shivanand • Edited
.parent {
display:flex;
}

.child {
margin:auto
}
Enter fullscreen mode Exit fullscreen mode

I learnt it from a youtube video and forgot the reference.

Collapse
 
hengage profile image
Henry Chizoba

I just tried this. Magical!

Collapse
 
danielpdev profile image
danielpdev

Nice collection of hacks for centering HTML elements!
As a best practice using flex or grid makes centering much more clear.

Collapse
 
makampos profile image
Matheus de Campos • Edited

Thanks bro!
By the way, I prefer using Flex for all cases, and you?

Collapse
 
akashvarma9 profile image
Akash Varma

Hi Matheus!
It depends on design. Even I prefer using Flex in all cases ✌️.

Collapse
 
akashvarma9 profile image
Info Comment hidden by post author - thread only accessible via permalink
Akash Varma

Oh, Can you elaborate on your issue, Ryan?

Some comments have been hidden by the post's author - find out more