Search Tools Links Login

Center a Div Horizontally and Vertically


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.

About this post

Posted: 2023-04-27
By: dwirch
Viewed: 257 times

Categories

Tip

Webmaster Related

CSS

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.