To vertically and horizontally center a div, you can use the below shown CSS code.
div
{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
This code sets the position of the div to “absolute”, which allows you to position it relative to its closest positioned ancestor. The “top” and “left” properties are then set to 50%, which places the top-left corner of the div in the center of its containing element.
Finally, the “transform” property is used to move the div back up and to the left by 50% of its own width and height, respectively. This centers the div both vertically and horizontally within its containing element.
Note that this method works only when the width and height of the div are fixed. If the width and height are variable, you may need to use JavaScript to calculate the center position dynamically.