How to horizontally center a <div> using CSS?

How can we horizontally center a <div> within another <div> using CSS?

Foo foo

Solution code for : How to horizontally center a <div> using CSS?

We can apply this CSS to the inner <div>:

HTML

Foo foo

CSS

#inner {
  width: 50%;
  margin: 0 auto;
}

Of course, we don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

If we are targeting IE8+, it might be better to have this instead:

HTML

Foo foo

CSS

#inner {
  display: table;
  margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width.

No comments:

Post a Comment