Connect with us

CSS

How to Align Text Vertically in CSS (with Examples)

Spread the love

Vertically aligning text in CSS can be tricky, especially when dealing with elements of varying height. Whether you’re working with a container, a table cell, or a flexbox, CSS provides multiple ways to vertically align text depending on the context.

In this guide, we’ll explore the most effective techniques for vertical text alignment with practical examples.


🎯 Common Use Cases

  • Centering text in a div (vertically and horizontally).
  • Aligning text inside a button or input.
  • Aligning labels next to form fields.
  • Vertically centering text in table cells.

✅ Method 1: Using Flexbox (Recommended for Modern Layouts)

🔹 Example

<div class="flex-container">
  <p>This text is vertically centered.</p>
</div>
.flex-container {
  display: flex;
  align-items: center;      /* Vertical alignment */
  justify-content: center;  /* Horizontal alignment */
  height: 200px;
  border: 1px solid #ccc;
}

✅ Why Use It?

  • Works on all modern browsers.
  • Easy and responsive.
  • Also aligns horizontally with justify-content.

✅ Method 2: Using line-height (Quick for Single Lines)

🔹 Example

<div class="line-height-box">Centered Text</div>
.line-height-box {
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px solid #aaa;
}

⚠️ Limitation:

  • Best for single-line text only.
  • Doesn’t work well for multi-line content.

✅ Method 3: Using vertical-align with Table Cells

🔹 Example

<div class="table-cell">
  <span>This text is centered vertically.</span>
</div>
.table-cell {
  display: table-cell;
  vertical-align: middle;
  height: 150px;
  width: 100%;
  border: 1px dashed #999;
}

📌 Tip:

Also works with real <table> and <td> elements.


✅ Method 4: CSS Grid (Elegant Modern Layout)

.grid-container {
  display: grid;
  place-items: center; /* Shorthand for both align & justify */
  height: 200px;
  border: 1px dotted #666;
}
<div class="grid-container">
  <p>Perfectly centered text.</p>
</div>

🛠 Use Case Comparison

MethodBest ForSupport
FlexboxAll content types✅ Modern
Line-heightSingle-line text✅ All
Table-cellOlder compatibility needs✅ All
GridModern, simple centering✅ Modern

🧾 Final Thoughts

Vertical alignment is no longer the challenge it used to be. Thanks to modern CSS tools like Flexbox and Grid, vertically centering text is quick, responsive, and clean.


Spread the love
Click to comment

Leave a Reply

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