DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

5

Why transform:translate(-50%, -50%) to center element?

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>



Enter fullscreen mode Exit fullscreen mode


.parent {
    position: relative;
    border: 1px solid green;
    display: inline-block;
    padding: 25px;
  }

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


Enter fullscreen mode Exit fullscreen mode

Without transform: translate(-50%, -50%);

Image description

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%);

Image description

Thanks,
Vishwak

Top comments (2)

Collapse
 
leopold profile image
Leopold •

Are there still reasons to use this technique in 2023 instead of flexbox or grid ?

Collapse
 
devdufutur profile image
Rudy Nappée •

Centering overlays (dialogs, sticky bars, ...) for instance

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay