如何摆脱带有浮动物品的容器右侧的空白空间?

时间:2016-04-07 15:56:51

标签: css

当我在容器中使用浮动itens时,例如:

代码(http://jsfiddle.net/tombrito/gx7kL330/7/):

.container {
  background: blue;
  position: absolute;
  width: auto;
}
.floating-box {
  float: left;
  width: 150px;
  height: 75px;
  margin: 10px;
  border: 3px solid #73AD21;  
}
<div class="container">
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
  <div class="floating-box">Floating box</div>
</div>

...如果我调整窗口大小,我会看到容器的width: auto不完全是内容的宽度:

enter image description here

右边有一些空白区域。有没有办法让容器真正成为漂浮孩子的宽度,即使我调整它的大小?

2 个答案:

答案 0 :(得分:0)

您可以使用flexbox规则。 (source

HTML:

<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
</ul>

的CSS:

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content: space-around;
}

.flex-item {
  background: red;
  padding: 5px;
  width: 200px;
  height: 150px;
  margin-top: 10px;
  line-height: 150px;
}

答案 1 :(得分:0)

如果jQuery是一个选项,我会做这样的事情;

$('body').on('resize', function () { 
    var width = document.documentElement.clientWidth || window.innerWidth,
        itemWidth = 150 + 20 + 6; //width + margin + border,
        count = Math.floor(width / itemWidth),
        containerWidth = itemWidth * count;

    $('.container').css('width', containerWidth + 'px'); 
});

//未经测试的代码警告