Strange margin on `display:inline-block`-elements

2020-07-23 03:56发布

I have 6 DIVs with display:inline-block in one line. But they have a strange white space between each other, how can I get rid of that? They should fit in the container in one line.

Fiddle: http://jsfiddle.net/y7L7q/

HTML:

<div id="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

CSS:

#container{
    width:300px;
    border:1px solid black;
}
.box{
    display:inline-block;
    height:50px;
    width:50px;
    background-color:black;
    margin:0;
    padding:0;
}

标签: html css
4条回答
霸刀☆藐视天下
2楼-- · 2020-07-23 04:38

Because they are set to inline block this means the whitespace between them is treated as inline whitespace, and therefore rendered as such. You can fix this by either by putting all the divs on one line in the html or wrapping the white space in comments:

<div class="box"></div><!--
--><div class="box"></div>
查看更多
【Aperson】
3楼-- · 2020-07-23 04:39

It's a common issue with display: inline-block. You have a few solution, delete new lines (or comment them : http://jsfiddle.net/eaqfk/), set font-size: 0, set margin-right: -4px.

Everything is on this question : CSS: Spacing issue with dropdown

查看更多
淡お忘
4楼-- · 2020-07-23 04:48

Instead of display:inline-block, use float:left to remove the unwanted space. Check this out.

http://jsfiddle.net/y7L7q/9/

Also note that font-size:0 is not the correct approach in my opinion as it will mess up the content inside those divs.

查看更多
聊天终结者
5楼-- · 2020-07-23 04:55

Write font-size:0;. Like this:

#container{
    width:300px;
    border:1px solid black;
    font-size:0;
}

Check this http://jsfiddle.net/y7L7q/1/

OR

Write your mark like this:

<div id="container">
    <div class="box"></div><div class="box"></div><div class="box"></div><div class="box"></div><div class="box"></div><div class="box"></div>
</div>

Check this http://jsfiddle.net/y7L7q/2/

查看更多
登录 后发表回答