0

The html and body is 100vh.

In my body, I have a 100px square.

When I apply top 50% to the div, the div, moves down 50%. But when I do apply translateY(50%) on the div, the div does not move down 50%?

Why is this?

Note: you have to open the html in a full page to see that the div does not move 50% down.

* {
  padding: 0;
  margin: 0;
}


html, body {
  height: 100vh;
  width: 100vw;
}

body {
  position: relative;
  background-color: black;
}

div {
  height: 100px;
  width: 100px;
  background-color: orange;
  position: absolute;
/*   top: 50%; */
  transform: translateY(50%);
}
<div></div>
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    `translate` is based on the size of the element it's attached to. `top` is based on the parent. So `top: 50%; transform: translateY(50%)` would be half way down the parent plus 50% of the element's height. – Phix Mar 04 '21 at 22:01
  • @Phix. Are you saying that translate moves the element based on its size? So if the div is a height of 100px. TranslateY(50%) would mean that div down 50px? –  Mar 04 '21 at 22:02
  • You can use `top: 50%;` and `left: 50%;`. – ublec Mar 04 '21 at 22:03
  • `top: 50%; transform: translate(-50%, -50%); left: 50%;` if you want it to be right in the center – curveball Mar 04 '21 at 22:04
  • @flow correct. see https://jsfiddle.net/31mg4x0r/ – Phix Mar 04 '21 at 22:09
  • very helpful demonstration –  Mar 04 '21 at 22:11

1 Answers1

0

top: 50% places the top of element at 50% of the container's height, so the top of the element in question is placed at the vertical center of the parent.

transform: translateY(50%) offsets the element by 50% of its own height. If the element is 100px tall it will move down 50px.

ray
  • 26,557
  • 5
  • 28
  • 27