• support@answerspoint.com

Horizontally center a div in a div

1888

How can I horizontally center a div within a div using CSS (if it's even possible)?

The outer div has 100% width:

 

<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>
 
  • html

  • asked 9 years ago
  • B Butts

2Answer


0

You can apply this CSS to the inner div:

#inner {
    width: 50%;
    /* Set the margin-left and margin-right automatically set */
    margin: 0 auto; 
}

Of course, you 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 you are targeting IE8+, it might be better to have this instead:

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

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

  • answered 8 years ago
  • Gul Hafiz

0

If you don't want to set a fixed width on the inner div you could do something like this:

#outer {
  width: 100%;
  text-align: center;
}

#inner {
  display: inline-block;
}

That makes the inner div into an inline element that can be centered with text-align.

  • answered 8 years ago
  • Sandy Hook

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 1888 times
  • active 9 years ago

Best Rated Questions