使用JS将div宽度调整为内容

时间:2016-04-19 10:04:33

标签: html css

设置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>

enter image description here

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。

enter image description here

1 个答案:

答案 0 :(得分:0)

将min-width:566px添加到容器中:

Add min-width