+ 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?
5 odpowiedzi
+ 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
+ 1
Abhishek Kudlur
See this example
https://code.sololearn.com/WGEQKFz4SsVh/?ref=app
0
Top:50% and left:50% made the div to center..
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?
0
Hanuma Ukkadapu thanks...