2 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
問題是,inline-block
默認(rèn)情況下,元素會(huì)使用一些額外的空間進(jìn)行渲染。
為什么?因?yàn)?code>divset inline-block
具有一些內(nèi)聯(lián)元素特征。
span
元素之間的空格或換行符將導(dǎo)致瀏覽器呈現(xiàn)的空間。
同樣,如果您在<p>
元素中編寫文本,則每次點(diǎn)擊空格鍵或添加換行符時(shí),瀏覽器都會(huì)呈現(xiàn)空格。
同樣的規(guī)則適用于inline-block
div。源中的空格或換行符將導(dǎo)致渲染空間。這會(huì)產(chǎn)生意外的寬度,從而導(dǎo)致溢出或纏繞。
一種解決方案是刪除源中元素之間的所有空格:
.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>
另一種方法設(shè)置font-size: 0
在父項(xiàng)上,如有必要,還可以恢復(fù)子項(xiàng)上的字體:
.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>
其他選項(xiàng)包括負(fù)邊距,省略結(jié)束標(biāo)記,使用注釋標(biāo)記,浮點(diǎn)數(shù)和彈性框。有關(guān)詳細(xì)信息,請參閱此文章:

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
我堅(jiān)持要你只添加一個(gè)屬性。一個(gè)刪除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 添加一個(gè)屬性。檢查更新的演示和SNIPPET。
注意:這會(huì)使
box
div中的文本保持對(duì)齊,所以如果你想讓它居中,只需在CSS中添加text-align:center;
你的.box
類。
添加回答
舉報(bào)