Connect with us

CSS

How to Align Text Vertically Center in a Div Element Using CSS

Spread the love

One of the most common tasks in web design is vertically centering text inside a div. Whether you’re building a landing page, button, or card component, centered text creates a clean and balanced layout.

Thankfully, modern CSS offers several efficient ways to align text vertically within a div. In this article, we’ll explore best practices and real code examples to help you center text like a pro.


βœ… Method 1: Using Flexbox (Most Popular)

πŸ”Ή HTML

<div class="flex-box">
  <p>Vertically centered text</p>
</div>

πŸ”Ή CSS

.flex-box {
  display: flex;
  align-items: center;      /* Align vertically */
  justify-content: center;  /* Align horizontally (optional) */
  height: 200px;
  border: 2px solid #4caf50;
}

βœ… Why Use It?

  • Works for both vertical and horizontal centering
  • Responsive and modern
  • Clean, readable code

βœ… Method 2: Using Grid Layout

πŸ”Ή HTML

<div class="grid-box">
  <p>Centered using CSS Grid</p>
</div>

πŸ”Ή CSS

.grid-box {
  display: grid;
  place-items: center; /* align-items + justify-items */
  height: 200px;
  border: 2px dashed #2196f3;
}

πŸ’‘ Benefits

  • Very concise
  • Perfect for simple centering tasks
  • Ideal when you don’t need complex layout control

βœ… Method 3: Using Line-Height (Only for Single Line Text)

πŸ”Ή HTML

<div class="line-height-box">Centered Text</div>

πŸ”Ή CSS

.line-height-box {
  height: 100px;
  line-height: 100px; /* Match the height */
  text-align: center;
  border: 2px dotted #ff9800;
}

⚠️ Caution

  • Only works properly for single-line text
  • Not suitable for multi-line paragraphs

βœ… Method 4: Table-Cell Technique (Legacy-Compatible)

πŸ”Ή HTML

<div class="table-cell-box">
  <p>Using table-cell alignment</p>
</div>

πŸ”Ή CSS

.table-cell-box {
  display: table-cell;
  vertical-align: middle;
  height: 150px;
  width: 100%;
  text-align: center;
  border: 1px solid #ccc;
}

πŸ“Œ Use Case

  • Great for older browser support
  • Slightly outdated in modern layouts

πŸ“Š Comparison Table

MethodMulti-line SupportModern SupportCode Simplicity
Flexboxβœ…βœ…βœ…
CSS Gridβœ…βœ…βœ…
Line-heightβŒβœ…βœ…
Table-cellβœ…βœ…βŒ (verbose)

🧾 Final Thoughts

If you’re working with modern browsers, Flexbox and Grid are the best tools for vertically centering text inside a div. They’re clean, flexible, and easy to maintain. For single-line text, the line-height trick is quick and effective. And when you need backward compatibility, the table-cell method is still a solid option.


Pro Tip: Combine vertical and horizontal centering to ensure your text looks centered across all screen sizes and resolutions.


Spread the love
Click to comment

Leave a Reply

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