Centering div or any element is the mostly asked question in CSS interviews. I am not going to write what are the different ways to achieve this. But, While I was doing this I observed that transform:translateY(-50%, -50%)
is used. I was little curious and wanted to know what it is actually doing.
Here is what I observed:
centering any element includes parent and child elements where child element is centered w.r.t parent.
<div class="parent">
<div class="child"></div>
</div>
.parent {
position: relative;
border: 1px solid green;
display: inline-block;
padding: 25px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Without transform: translate(-50%, -50%);
Here parent div is circle and the child is number 1.
As we set top and left is 50% for child resulting in placing 50% from parent top and 50% from parent left. It will show like above because starting of child starts after 50%, 50% but to make it center we need to apply transform: translate(-50%, -50%);
. This moves the child element back up a distance of half of the height and width. As it will make child element matches exactly to the middle of parent.
After adding transform: translate(-50%, -50%);
Thanks,
Vishwak
Top comments (2)
Are there still reasons to use this technique in 2023 instead of flexbox or grid ?
Centering overlays (dialogs, sticky bars, ...) for instance