2016-04-07 48 views
2

当我使用浮动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

右侧有一些空白区域。有没有办法让容器真的成为浮动儿童的宽度,即使我调整它的大小?

+0

尝试回答这个问题(http://stackoverflow.com/questions/18482505/having-the-floating-children-elements-determine-parent-width)但我认为如果你有更多的元素让它们缠绕,你会很困难...... – Stuart

+0

如果你使用引导程序,那么它会很容易,或者你可以为它做一个jquery函数。 –

+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; 
} 
+0

不...不是......你真的不能......甚至flexbox都无法做到这一点。这不是OP要找的。 –

+0

这将分配空间中的框,但我真的想使容器很小,以适应内容的大小。无论如何,有趣的了解这个属性... :) –

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'); 
}); 

//未经测试的代码警告