Nick Bull Blog

Nick Bull Blog

How to horizontally center a <div>? (HTML/CSS)

How to horizontally center a <div>? (HTML/CSS)

You have a problem

You want to horizontally center a <div> within another <div> using CSS.

Example of your situation:

Here's how to do it.

Solution #1

The first solution is to apply the CSS property margin and width to the inner element you want to center horizontally.

Example:

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

#inner {
  margin: 0 auto;
  width: 100px;
}

Result:

You can add any width, not just 100px.

Solution #2

The next solution is more common and simpler.

Apply CSS flexbox property to center your element horizontally.

Example:

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

Result:

Solution #3

The last solution is to center your div using position: absolute; and transform properties.

Example:

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

#inner {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

Result:

In the end...

Hope you found these solutions to center div horizontally 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