8 ways to center a div: The most common interview question

Sahil Garg
3 min readSep 22, 2023

--

Centering a div is now a meme on internet but still to this day it is very common among software developers that they are not familiar either with all the ways or sometimes even with one. Having a knowledge of all these ways is a great asset in your skill set and efficiency as a web developer.

The 8 ways are given below with the CSS code (and HTML code just for one) that needs to be applied to the elements. The HTML document structure for all the examples is as below:

<div class="parent">
<div class="child">
Hello world!
</div>
</div>

1. Position absolute

Centers both vertically and horizontally
Position absolute brings the element out of the normal document flow. Then then we shift the top edge of the element 50% (of the document height) to the bottom and similarly the left side 50% (of the document width) to the right.

.parent {
position: relative;
}

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

2. Margin auto

Centers only horizontally
If we set the width of parent element to the appropriate size, making the child element of a set width less than the parent element, we can set the…

--

--

Sahil Garg
Sahil Garg

Written by Sahil Garg

Helping aspiring developers become better in the web dev game! UG Researcher, Chairperson at CCET ACM Student Chapter

No responses yet