+ 1

How does this work?

HTML: <div></div> CSS: #div{ position: absolute; top:50%; left:50%; transform: translate (-50%,-50%); } This code centers the div element. How does it work?

26th Jul 2020, 3:56 AM
Abhishek Kudlur
5 ответов
+ 1
Abhishek Kudlur Transform: translate(-50%,-50%) translates the center of that element to the top left of the document which is at (0,0). [ Edit ]: It translates the element in both x and y directions by a distance equal to 50% of document(i.e. viewport) width and height. And as the distance mentioned is negative, it moves up and to its left. That means now the element's starting point is at its center. Then by doing top: 50% and left: 50% makes the element's starting point(which is now it's center) to be centred at the document center
26th Jul 2020, 6:02 AM
Hanuma Ukkadapu
Hanuma Ukkadapu - avatar
26th Jul 2020, 6:11 AM
Hanuma Ukkadapu
Hanuma Ukkadapu - avatar
0
Top:50% and left:50% made the div to center..
26th Jul 2020, 3:58 AM
Mustafha Ahmad
Mustafha Ahmad - avatar
0
Mustafha Ahmad no that doesn't move the div element to the center. "transform:translate(-50%,-50%)" with them makes it. But I don't know how?
26th Jul 2020, 4:30 AM
Abhishek Kudlur
0
Hanuma Ukkadapu thanks...
26th Jul 2020, 6:07 AM
Abhishek Kudlur