frosty
frosty

Reputation: 2649

Make the width of outer div to fit inner divs automatically

I have 2 inner divs inside an outer div, and I want to make the outer div to automatically fit to the width of the inner divs. Is that possible?

body {
  font-size: 0;
}
#outer {
  border: 1px solid black;
}
.inner {
  font-size: 12px;
  display: inline-block;
  border: 1px solid red;
}
<div id='outer'>
  <div class='inner'>text1</div>
  <div class='inner'>text2</div>
</div>

Upvotes: 15

Views: 31283

Answers (3)

DC319
DC319

Reputation: 119

If you add position:absolute; or float:left; to #outer it will size to the two inner div's. For this instance, I would use the float. Floats are generally better for content that might change or expand/shrink with edits over time whereas absolute positioning should be used outside of the document flow or structure of the document, like a nav bar.

Edit: If you don't need other elements to flow around the outer div the display:inline-block method posted below will work, but if you have elements you want to flow around #outer then float:left would be the way to go. Say you have #outer as 50% of the width and want something else on the other half of the page using display:inline-block will put other elements below #outer.

CodePen link to show difference

Upvotes: 0

RyanT
RyanT

Reputation: 137

Add "display: table;" to the #outer css:

For example:

#outer {
    border: 1px solid black;
    display: table;
}

using display: table is less intrusive as using inline

Upvotes: 5

Satwik Nadkarny
Satwik Nadkarny

Reputation: 5135

Your outer div is a block-level element. You need to make it an inline-level element. Inline elements automatically take the size of the content it contains. In terms of the question you've asked, just setting :

display: inline-block

on your outer div will do the trick. See the code snippet below for the demo :

  body {
      font-size: 0;
    }
    #outer {
      border: 1px solid black;
        display: inline-block;
    }
    .inner {
      font-size: 12px;
      display: inline-block;
      border: 1px solid red;
    }
<div id='outer'>

  <div class='inner'>
    text1
  </div>
  <div class='inner'>
    text2
  </div>

</div>

Hope this helps!!!

Upvotes: 26

Related Questions