Make the width of the outer div so that it matches the inner divs automatically

I have 2 inner divs inside the outer div, and I want the outer div to automatically match the width of the inner divs. Is it 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> 
+6
source share
3 answers

Your outer div is a block level element. You must make it an element of the built-in level. Inline elements automatically take the size of the content contained in it. Regarding the question you asked, just install:

 display: inline-block 

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

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

+8
source

Add "display: table;" on #outer css:

For instance:

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

using the display: the table is less intrusive than using the built-in

+1
source

If you add position:absolute; or float:left; in #outer , the size will be equal to two inner div . For this example, I would use a float . Floats are usually better for content that can change or expand / shrink with changes over time, while absolute positioning should be used outside the document flow or document structure, for example, in the navigation bar.

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

CodePen link to show the difference

0
source

All Articles