How can I center text (horizontally and vertically) inside a div block?

To center text both horizontally and vertically inside a div, you can use one of these CSS methods:

1. Flexbox (Modern & Recommended)

.container {
  display: flex;
  justify-content: center; /* Horizontal centering */
  align-items: center;     /* Vertical centering */
  height: 300px;          /* Explicit height required */
  width: 100%;
}

HTML:

<div class="container">
  Centered Text
</div>

2. CSS Grid

.container {
  display: grid;
  place-items: center; /* Centers both axes */
  height: 300px;
}

3. Absolute Positioning + Transform

Works without needing a parent container height:

.container {
  position: relative;
  height: 300px;
}

.centered-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* Adjusts for element's own size */
}

HTML:

<div class="container">
  <div class="centered-text">Centered Text</div>
</div>

4. Line-Height (Single-Line Text Only)

.container {
  height: 300px;
  line-height: 300px; /* Matches container height */
  text-align: center;
}

Comparison Table

MethodBest ForBrowser Support
FlexboxModern layoutsAll modern browsers
CSS GridModern layoutsAll modern browsers
Absolute + TransformLegacy/unknown heightsAll browsers
Line-HeightSingle-line textAll browsers

Full Example (Flexbox)

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      width: 400px;
      border: 2px solid #333;
      background: #f0f0f0;
    }
  </style>
</head>
<body>
  <div class="container">
    Perfectly Centered Text
  </div>
</body>
</html>

Key Notes:

  • Use Flexbox or Grid for modern projects.
  • Use Absolute Positioning for legacy browser support.
  • Avoid line-height for multi-line text (use flexbox instead).

Leave a Reply

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