0

Good day! I'm studying on how to align text vertically at center. I'm trying to know why is the transform:translateY(50%) moves just a bit and transform:translateX(50%) moves quite a lot.

I've tried moving my element using an exact px value and I somehow get it on how it works but using percentage like this transform:translateY(-50%), I'm confused.

<head>

  <style type="text/css">
    .Container {
      background-color: #85C1E9;
      height: 200px;
      width: 200px;
    }
    
    .Content {
      position: relative;
      transform: translateY(50%);
      transform: translateY(50%);
    }
  </style>


</head>

<body>

  <div class="Container">

    <div class="Content">

      <p>Hello</p>

    </div>

  </div>


</body>

I just want to know why if I use translateX(50%), the element moves a lot farther and when it's translateY(50%) it does move, but just a little.

Akshay Mulgavkar
  • 1,727
  • 9
  • 22

2 Answers2

0

When using translate, movement is relative to the size of the box.

Let's say you have a div that's 200px x 50px. If you use translateX(50%), you're going to move the element to the right by 50% of its width (100px).

If you were to use translateY(50%) by contrast, you'd move it down by 50% of its height which in this case would be 25px.

To your specific example, you have a 200px x 200px container. That's not the element that you're applying translate to however. Instead you're moving the .Content div within your container. Since you haven't given that element a defined size, it's going to be 200px x the height of your paragraph. The height is considerably less than the width, hence the difference in movement distance between the two forms of translate.

Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
0

The transform:translateY(50%) works on the dimensions of the element being applied on. If the element's width is more than it's height, then it moves less as compared to transform:translateX(50%).

Also, you may notice similar thing (but not to same extent) if the element have same width and height, because of the resolution of the device you are working, as they usually have different number of pixels on a row as compared to column. I hope this helps.

Waleed Iqbal
  • 1,308
  • 19
  • 35