Setting display: inline-block
should make the surrounding div not larger than its content: How to make div not larger than its contents?
However, when line-breaks are included it does 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 is stated in CSS when inline-block elements line-break, parent wrapper does not fit new width that one can correct the width of the DIV with jQuery. How would you do it for this example?
Answer The question is marked as a duplicate, so I cant give an answer, but this worked for 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 is 90px (50+20+20), so set width to the minimal width which // is dividible by 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 the boxes are inline-elements, I needed to remove the whitespace, otherwise they don't fit in the div.