15

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>

1
  • Good question frosty :+1 Useful to know when creating a progress bar Sep 18, 2021 at 15:42

3 Answers 3

22

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!!!

2
  • but when there isn't enough space, and the inner divs wrap on two lines, then the outer div is larger than the inner div. How can this be changed?
    – bersling
    Apr 3, 2020 at 18:12
  • 1
    that helped Satwick :+1 Sep 18, 2021 at 15:40
3

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

1
  • 1
    After 5 years this is the best answer, I was trying to fix some absolute positioned tooltips inside td elements of a table, but they didn't expand over the td width. Now are perfect. Oct 15, 2020 at 8:02
0

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.