html - Adjust div width to content with JS -
this question has answer here:
setting display: inline-block
should make surrounding div not larger content: how make div not larger contents?
however, when line-breaks included not work (jfiddle)):
<style> .container{ border: solid; display: inline-block } .box{ background-color: #08c; width: 50px; height: 50px; margin: 20px; display: inline-block; } </style> <div class='container'> <div class='box'></div> <div class='box'></div> <div class='box'></div> <div class='box'></div> <div class='box'></div> <div class='box'></div> </div>
it stated in css when inline-block elements line-break, parent wrapper not fit new width 1 can correct width of div jquery. how example?
answer question marked duplicate, cant give answer, worked me (jfiddle):
<style> .container{ border: solid; display: inline-block; } .box{ background-color: #08c; width: 50px; height: 50px; margin: 20px; display: inline-block; } </style> <script> function adjust(){ // reset container width $('.container').width(''); var x = $('.container').width(); // size of box 90px (50+20+20), set width minimal width // dividible 90px x= x - (x % 90); $('.container').width(x); } $(document).ready(function(){ adjust(); $(window).resize(adjust); }); </script> <div class='container'> <div class='box'></div><!-- --><div class='box'></div><!-- --><div class='box'></div><!-- --><div class='box'></div><!-- --><div class='box'></div><!-- --><div class='box'></div> </div>
also since boxes inline-elements, needed remove whitespace, otherwise don't fit in div.
Comments
Post a Comment