设置display: inline-block
会使周围的div不大于其内容:How to make div not larger than its contents?
但是,当包含换行符时,它不起作用(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>
在CSS when inline-block elements line-break, parent wrapper does not fit new width中声明可以使用jQuery更正DIV的宽度。你会怎么做这个例子?
回答问题被标记为重复,所以我无法给出答案,但这对我有用(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>
此外,由于框是内联元素,我需要删除空格,否则它们不适合div。