How to Center a Div Vertically and Horizontally

How to Center a Div Vertically and Horizontally

Centering a <div> both vertically and horizontally is a common requirement in web development. Here are multiple methods to achieve this using CSS.

Step 1: HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Center a Div Vertically and Horizontally (CSS Methods)</title>
    <meta name="description" content="Learn how to center a div both vertically and horizontally using CSS Flexbox, Grid, and traditional methods. Step-by-step guide with code examples.">
    <meta name="keywords" content="CSS, HTML, center div, Flexbox, Grid, position absolute, web development, frontend">
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 50px;
            background-color: #f4f4f4;
        }
</head>
<body>

<div class="center-flex">
  <div>Your content here</div>
</div>

</body>
</html>

1. Using Flexbox (Recommended)

.center-flex {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Full viewport height */
}

2. Using CSS Grid

.center-grid {
  display: grid;
  place-items: center;
  height: 100vh;
}

3. Using Position Absolute & Transform

.center-absolute {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Conclusion

  • Flexbox is the easiest and most flexible method.
  • Grid is great for layouts that need centering.
  • Position Absolute & Transform works well for absolute positioning.

Leave a Reply

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

Scroll to Top