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.
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.
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:
