2016-07-25 42 views
0

我试图创建4个盒子左侧宽度为25%,margin:0 10px在侧面给予间隔,但最后一个div被压下。问题创建浮动左宽具有相同宽度的div盒

我试过应用盒子大小,但它没有做任何事情。

Plunker link

<div class="box">1</div> 
<div class="box">2</div> 
<div class="box">3</div> 
<div class="box">4</div> 

.box { 
    width: 25%; 
    background: #333; 
    float: left; 
    color: #fff; 
    margin: 0 10px; 
    padding: 10px; 
} 
+0

的div大小为25% - 但它是加保证金左/右10px,所以它们不是均匀间隔。 – Toby

+1

使用'box-sizing:border-box'尝试'width:calc(25% - 20px)' – Pete

+0

您的案例中的总宽度为100%+ 40px> 100%。这就是为什么最后一个div被推倒了。 – semanser

回答

2

按我的意见:

尝试width: calc(25% - 20px)box-sizing: border-box

.box { 
 
    width: calc(25% - 20px); /* takes care of margin */ 
 
    background: #333; 
 
    float: left; 
 
    color: #fff; 
 
    margin: 0 10px; 
 
    box-sizing: border-box; /* takes care of padding */ 
 
    padding: 10px; 
 
}
<div class="box">1</div> 
 
<div class="box">2</div> 
 
<div class="box">3</div> 
 
<div class="box">4</div>

如果你不能得到的钙工作,你可以只取出保证金和使用一个内盒(我通常做什么,使之兼容的老版本浏览器):

.box { 
 
    width: 25%; 
 
    box-sizing: border-box; 
 
    padding: 0 10px; 
 
    float: left; 
 
} 
 
.box .inner { 
 
    background: #333; 
 
    color: #fff; 
 
    padding: 10px; 
 
}
<div class="box"><div class="inner">1</div></div> 
 
<div class="box"><div class="inner">2</div></div> 
 
<div class="box"><div class="inner">3</div></div> 
 
<div class="box"><div class="inner">4</div></div>

+0

怪异的calc正在读取px作为%它给我总共5%的宽度。 – nCore

+0

haha​​ha,很奇怪你使用的是什么浏览器 - 这是一个新的CSS的事情,只支持在较新的浏览器 – Pete

+0

我知道的权利,我以前使用过钙,但从来没有尝试过%减px。我现在正在使用chrome,很确定chrome使用calc只是这个很奇怪。 – nCore

0

就像@toby说你要减少你的宽度的百分比。随着填充你结束了超过100%。该最小的我能得到它的工作是18%

.box { 
 
    width: 18%; 
 
    background: #333; 
 
    float: left; 
 
    color: #fff; 
 
    margin: 0 10px; 
 
    padding: 10px; 
 
}
<div class="box">1</div> 
 
<div class="box">2</div> 
 
<div class="box">3</div> 
 
<div class="box">4</div>

+0

我不想减小盒子的宽度,因为这会使它对我的需要太小。 – nCore

+0

你需要减少一些东西。填充为10px,宽度为25%时,数字不加起来。 –