删除 div 之间的 space

remove space between divs

问题:为什么两个div标签之间有一个space?

Here is the JSFiddle

截图:

//HTML

<div class='row'>
    <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
    </div>
    <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
    </div>
</div>

//CSS

.row{
    background-color: red; 

    margin: 2em 0;
    display: block;
    text-align: center;
    white-space: nowrap;
    -webkit-box-shadow: 0 1px 5px rgba(0,0,0,.6) inset;
    box-shadow: 0 1px 5px rgba(0,0,0,.6) inset;  
}
.item{
    background-color: silver;

    width: 50%;
    white-space: normal;
    display: inline-block;
}
.sub-item{
    background-color: royalblue;

    margin: .5em;
    width: 100px;
    height: 100px;
    text-align: center;
    display: inline-block;
}

Why is there a space between the two div tags?

您可以在 Fighting the Space Between Inline Block Elements

中阅读更多相关信息

要删除不需要的空白space,请在.row元素中设置font-size: 0,然后在.item中恢复font-size

.row {
    font-size: 0;
}

.item {
    font-size: 12px;
}

由于您的边距使用 em 单位,如果您简单地在包装元素中设置 font-size: 0,您的边距也会消失。

为了保持边距,重要的是恢复内部元素中的字体大小或使用不基于字体大小的其他单位设置边距,例如 px

示例如下:

.row {
  background-color: red;
  margin: 2em 0;
  display: block;
  text-align: center;
  white-space: nowrap;
  -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, .6) inset;
  box-shadow: 0 1px 5px rgba(0, 0, 0, .6) inset;
  font-size: 0;
}
.item {
  font-size: 12px;
  background-color: silver;
  width: 50%;
  white-space: normal;
  display: inline-block;
}
.sub-item {
  background-color: royalblue;
  margin: .5em;
  width: 100px;
  height: 100px;
  text-align: center;
  display: inline-block;
}
<div class='row'>
  <div class="item">
    <div class="sub-item"></div>
    <div class="sub-item"></div>
    <div class="sub-item"></div>
    <div class="sub-item"></div>
    <div class="sub-item"></div>
  </div>
  <div class="item">
    <div class="sub-item"></div>
    <div class="sub-item"></div>
    <div class="sub-item"></div>
    <div class="sub-item"></div>
    <div class="sub-item"></div>
  </div>
</div>

有多种方法可以删除元素之间的 space... 一种方法是简单地让标签字面上粘在一起,例如 </div><div>

<div class='row'>
    <div class="item">
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
    </div
    ><div class="item"> <-- an end tag stick with another open tag will solve your problem
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
        <div class="sub-item"></div>
    </div>
</div>

更多其他解决方案,也可以看这里CSS-Trick