內嵌塊盒不適合其容器不知道我做錯了什么,我認為通過添加邊框,它將整齊地適合那4個盒子。http://jsfiddle.net/jzhang172/x3ftdx6n/.ok{width:300px;
background:red;
height:100px;
box-sizing:border-box;}.box{
display:inline-block;
box-sizing:border-box;
width:25%;
border:2px solid blue;
height:100%;}<div class="ok"><div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div>
</div>
2 回答

慕妹3242003
TA貢獻1824條經驗 獲得超6個贊
問題是,inline-block
默認情況下,元素會使用一些額外的空間進行渲染。
為什么?因為div
set inline-block
具有一些內聯元素特征。
span
元素之間的空格或換行符將導致瀏覽器呈現的空間。
同樣,如果您在<p>
元素中編寫文本,則每次點擊空格鍵或添加換行符時,瀏覽器都會呈現空格。
同樣的規則適用于inline-block
div。源中的空格或換行符將導致渲染空間。這會產生意外的寬度,從而導致溢出或纏繞。
一種解決方案是刪除源中元素之間的所有空格:
.ok { width: 300px; background: red; height: 100px; box-sizing: border-box;}.box { display: inline-block; box-sizing: border-box; width: 25%; border: 2px solid blue; height: 100%;}
<div class="ok"><div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div></div>
另一種方法設置font-size: 0
在父項上,如有必要,還可以恢復子項上的字體:
.ok { width: 300px; background: red; height: 100px; box-sizing: border-box; font-size: 0;}.box { display: inline-block; box-sizing: border-box; width: 25%; border: 2px solid blue; height: 100%; font-size: 16px;}
<div class="ok"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> <div class="box">4</div></div>
其他選項包括負邊距,省略結束標記,使用注釋標記,浮點數和彈性框。有關詳細信息,請參閱此文章:

ITMISS
TA貢獻1871條經驗 獲得超8個贊
我堅持要你只添加一個屬性。一個刪除box
div 之間的空格。只需添加float:left;
到您的.box
class / div。
.ok{ margin:0px auto; /* ADDED */ width:300px; background:red; height:100px; box-sizing:border-box; padding:0px auto;}.box{ display:inline-block; box-sizing:border-box; width:25%; border:2px solid blue; height:100%; float:left;}
<div class="ok"><div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div> </div>
更新:要使它居中,只margin:0px auto;
為您的.ok
類/ div 添加一個屬性。檢查更新的演示和SNIPPET。
注意:這會使
box
div中的文本保持對齊,所以如果你想讓它居中,只需在CSS中添加text-align:center;
你的.box
類。
- 2 回答
- 0 關注
- 611 瀏覽
相關問題推薦
添加回答
舉報
0/150
提交
取消