Nick Bull Blog

Nick Bull Blog

How to center text horizontally and vertically inside a div block? (HTML/CSS)

How to center text horizontally and vertically inside a div block? (HTML/CSS)

You have a problem

You want to horizontally and vertically center text in a <div> block using CSS.

Example of your situation:

Here's how to do it.

Solution #1 (modern)

The first solution that used widely is to use the flexbox property to center the inner text.

Example:

<div id="outer">
  <p id="inner">Center me</p>
</div>
#outer {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #eba300;
  height: 300px;
}

Result:

Solution #2

The next solution is to use position: absolute and transform: translate properties to center text inside div.

Example:

<div id="outer">
  <p id="inner">Center me</p>
</div>
#outer {
  position: relative;
  background: #eba300;
  height: 300px;
}

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

Result:

Solution #3

And the last solution is to use text-align: center, vertical-align: middle and line-hiehgt properties.

Set line-height height the same as parent div height.

Example:

<div id="outer">
  <p id="inner">Center me</p>
</div>
#outer {
  position: relative;
  background: #eba300;
  height: 300px;
}

#inner {
  text-align: center;
  vertical-align: middle;
  line-height: 300px;
}

Result:

In the end...

Hope you found these solutions to center text useful!

I share a lot of useful HTML, CSS, and JavaScript tips on Twitter, if you want to upgrade your skills don't forget to follow me (or just to say Hi).

And also, every week I send out a "3–2–1" newsletter with 3 tech news, 2 articles, and 1 piece of advice for you.

📌 Subscribe to my 3–2–1 newsletter! 📌

 
Share this