How to make a <div> expand nested in its contents?

I use this system to try to implement a sliding window selector.
I have a <div> which is contained in another <div> . The outer <div> has a fixed size, and the inner one must expand to contain its contents.

 <div style="width: 25px; overflow: hidden"> <div id="middle"> <div style="width: 50px"></div> </div> </div> 

The external <div> has a fixed size.
middle <div> must expand to fit the size of the internal <div> (one that is 50 pixels wide)
How, using CSS or JavaScript, can I ensure that the middle <div> is as wide as the internal <div> , but is still disabled by the external <div> ?

I tried using jQuery to get the length of the inner <div> , and then dynamically set the width of the middle of the <div> , but this does not always give the correct length.

+4
source share
6 answers

Div elements by default try to set their container. so the middle one will try to match its container, which is the outer div .. the content is not affecting it.

If you set the middle display:inline-block , you will make it suitable for the content, not the container, which fixes the problem.

+6
source

Can you make an inner div float? Thus, it should display the full width of the range, but without editing the outer width of the div, in order to expand the content longer than the outer width of the div will be invisible.

0
source

divs are block elements, so your inner div naturally expands to the width of the containing div. This can be done by setting the style attribute of the inner div to 100%. You must also set the CSS overflow property to "hidden".

0
source

You can get the width of the content of any HTML object as follows:

 document.getElementById("myDIV").clientWidth 
0
source

Use display: inline-block and max-width: ?px on middle . You will want to put overflow-x: hidden on middle (not outer as in your code), but I left it in the demo so you can see how width works.

Demo: http://jsfiddle.net/ThinkingStiff/hHDQS/

HTML:

 <div class="outer"> <div class="middle"> <div id="inner1"></div> </div> </div> <div class="outer"> <div class="middle"> <div id="inner2"></div> </div> </div> 

CSS

 .outer { border: 1px solid green; height: 100px; width: 300px; } .middle { border: 1px solid red; display: inline-block; height: 75px; max-width: 300px; } #inner1 { border: 1px solid blue; height: 50px; width: 50px; } #inner2 { border: 1px solid blue; height: 50px; width: 350px; } 

Output:

enter image description here

0
source

If the inner div can be absolutely positioned, the following stretches it to completely fill the parent element (width and height):

 #myInner{ position:absolute; left:0; right:0; top:0; bottom:0; width:auto; height:auto; } 
0
source

Source: https://habr.com/ru/post/1386426/


All Articles