Center a Div Horizontally and Vertically

By | 2023-04-27

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.

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.