How to center an element horizontally and vertically
How to center an element horizontally and vertically
390
24-Apr-2023
Updated on 25-Apr-2023
Aryan Kumar
25-Apr-2023To center an element both horizontally and vertically, you can use CSS styling. Here's an example of how to do it:
HTML code:
CSS Code:
In this example, we're using the div element, but you can replace it with any other element you want to center. We're setting the position property to absolute to take the element out of the normal flow of the page. The top: 50%; and left: 50%; properties will position the top-left corner of the element at the center of its container.
Finally, we're using the transform property to shift the element up and to the left by half of its own width and height, effectively centering it both horizontally and vertically. The translate(-50%, -50%) value of the transform property does this by shifting the element 50% of its width to the left and 50% of its height up.
Note that this method assumes that the element has no other content or padding within it, and that its container has position: relative; set. If these assumptions don't hold, you may need to adjust the CSS code accordingly.