1

I have 2 divs. One inside of another. The one on the outside has a width and height of 500px, and the one on the inside have a width of auto. I'm trying to center the div on the inside, but I'm also trying to get the width of it to be auto. It's not adjusting the width to auto, and instead it's spanning the entire 500px of the outer div. I'm not sure what I did wrong, so please take a look at my code:

<style>

#outer {
border: 1px solid black;
width: 500px;
height: 500px;
}
#inner {
border: 1px solid black;
width: auto;
margin: auto;
}

</style>

<div id = 'outer'>

<div id = 'inner'> Inner </div>

</div>
frosty
  • 2,559
  • 8
  • 37
  • 73
  • There is some contradiction in your logic, setting your inner width to auto will in fact inherit from the outer width, so it will take 500px width also, which visually will not do anything it will take the hole 500px as a result you will get the inner div overriding the hole space of the outer div ... if you want to center the inner you must reduce inner width set it to 400px for example ... is this what you want ? or you want to vertically center your inner ? – Mohamed Salem Lamiri Jul 15 '15 at 23:56

1 Answers1

1

Div's are display: block which defaults to filling the entire width of the parent. So when you are setting it to width: auto it's doing the default. If you want to make it conform to it's content, then set it to display: inline-block. Since inline-block can be centered like text just add text-align: center to your #outer div. Like so:

#outer {
  border: 1px solid black;
  width: 500px;
  height: 500px;
  text-align: center;
}
#inner {
  border: 1px solid black;
  display: inline-block;
}
<div id='outer'>
  <div id='inner'>Inner</div>
</div>
David Mann
  • 2,074
  • 1
  • 17
  • 17