0 votes
1 view
in Web Technology by (16.2k points)

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

<div id="outer">  

  <div id="inner">Foo foo</div>

</div>

1 Answer

0 votes
by (34.9k points)

Try using this CSS code to the inner <div>:

#inner {

  width: 50%;

  margin: 0 auto;

}

Note: It's not needed to set the width to 50%. Since any width less than the containing <div> will work. But you must add the margin: 0 auto because this will help you in actual centering.

But if you are working on IE8+ browser, then the below code will be the right choice for you:

#inner {

  display: table;

  margin: 0 auto;

}

 The above code will make the inner element center horizontally and it'll work without setting a specific width.

For example:

#inner {

  display: table;

  margin: 0 auto;

  border: 1px solid black;

}

#outer {

  border: 1px solid red;

  width:100%

}

<div id="outer">

  <div id="inner">Foo foo

</div>

...