How do I vertically align text in a div?

To vertically align text within a div, use one of the following CSS methods depending on your needs:

1. Using Flexbox (Modern & Recommended)

Center text vertically and/or horizontally within a container:

.container {
  display: flex;
  align-items: center;      /* Vertical alignment */
  justify-content: center; /* Horizontal alignment */
  height: 200px;           /* Container must have a height */
}

Example:

<div class="container">
  <p>Vertically and horizontally centered text</p>
</div>

2. Using CSS Grid

Center content vertically and horizontally:

.container {
  display: grid;
  place-items: center; /* Centers content in both directions */
  height: 200px;
}

3. Using line-height (Single Line Only)

For single-line text, match line-height to the container’s height:

.container {
  height: 200px;
}

.container p {
  line-height: 200px; /* Matches container height */
  margin: 0;          /* Removes default paragraph margins */
}

4. Using Absolute Positioning

Manually center content using transform (works for dynamic heights):

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

.container p {
  position: absolute;
  top: 50%;
  transform: translateY(-50%); /* Shifts element up by half its height */
  margin: 0;
}

5. Using vertical-align with Table Display

Simulate table behavior for vertical alignment:

.container {
  display: table;
  height: 200px;
  width: 100%;
}

.container p {
  display: table-cell;
  vertical-align: middle; /* Aligns text vertically */
  text-align: center;     /* Aligns text horizontally */
}

Key Notes

  • Multi-Line Text: Use Flexbox or Grid for multi-line content.
  • Dynamic Height: Avoid line-height for containers with variable heights.
  • Browser Support: Flexbox and Grid work in modern browsers (IE11+ with prefixes).
  • Horizontal Alignment: Add justify-content: center (Flexbox) or text-align: center (other methods).

Example: Vertical + Horizontal Centering with Flexbox

<div class="flex-container">
  <p>Centered text</p>
</div>

<style>
.flex-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  border: 1px solid #ccc;
}
</style>

Choose the method that best fits your layout requirements and browser support needs. Flexbox/Grid are the most versatile solutions.

Leave a Reply

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