如何去除div元素之间的间距?

3
为什么
之间会有空白边距?我尝试了不同的方法去除它,但都没有起作用。我只好减小它们的宽度以便将它们堆叠在行中。

*{
  box-sizing: border-box;
}

.wrapper{
  background-color: #ccc;
  width: 500px;
  margin: 5% auto;
  padding: 0;
}

.box{
  display: inline-block;
  margin: 0px;
  background-color: #f1f1f1;
  width: 248px;
  height: 250px;
  border: 0 !important;
  font-size: 0;
}
<div class="wrapper">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


1
这里的盒子没有边距。 - Jishnu V S
1
尝试在包装器上使用font-size:0px;进行实验,因为在您的HTML代码中div之间存在空格。 - phip1611
1
这个问题之前已经在这里得到解答 - https://dev59.com/Dm445IYBdhLWcg3wBVzz - larrydalmeida
7个回答

3
将.box的宽度设为250像素,并在.box中添加'float: left'属性。
.box{
display: inline-block;
margin: 0px;
padding: 0;
background-color: #ff9900;
width: 250px;
height: 250px;
float: left;
}

Fiddle


2
由于使用了display: inline-blocks,在块元素之间出现了空白。有多种解决方法,请参考David Walsh的博客
我更喜欢在这里使用float而不是display: inline-block
请参考以下代码:

*{
  box-sizing: border-box;
}

.wrapper{
  background-color: #ccc;
  width: 500px;
  margin: 5% auto;
  padding: 0;
}

.box{
  float: left;
  margin: 0px;
  background-color: #f1f1f1;
  width: 248px;
  height: 250px;
}
<div class="wrapper">
  <div class="box">
    
  </div>
  <div class="box">
    
  </div>
  <div class="box">
    
  </div>
  <div class="box">
    
  </div>
</div>


2

不是margin导致两个div之间有空隙,而是因为你给box类添加了display:inline-block属性,只需将其改为float:left;即可消除空隙。

*{
  box-sizing: border-box;
}

.wrapper{
  background-color: #ccc;
  width: 500px;
  margin: 5% auto;
  padding: 0;
}

.box{
display: inline-block;
margin: 0px !important;
background-color: #f1f1f1;
width: 248px;
height: 250px;
border: 0 !important;
float: left;
}
<div class="wrapper">
  <div class="box" style="background: rebeccapurple;">
    
  </div>
  <div class="box"  style="background: orange;">
    
  </div>
  <div class="box" style="background: orange;">
    
  </div>
  <div class="box" style="background: rebeccapurple;">
    
  </div>
</div>


2
问题在于div之间有空隙。有两种可能的解决方案:
1:
<div class="wrapper">
  <div class="box">

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

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

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

  </div>
</div>

-

.box { display: block; } // not multiple elements in one line, if you want this

2:

.wrapper { font-size: 0px; }
.box { display: block; } // not multiple elements in one line, if you want this

1
尝试在所有受影响的 div 上设置 border: 0 !important,我曾遇到类似问题,发现这些 div 继承了一个 1px 的边框,导致宽度出现问题。

1
没有效果。div 没有边框。 - Anurag Awasthi

1
你正在将它们显示为内联块,因此在代码格式化中它们之间的空白仍然会被显示,就像它们是其他任何内联元素一样。
你需要重新格式化代码,或将包装器设置为零字号,以便它们不会被呈现。

1
尝试使用 <\p>。
*{
  box-sizing: border-box;
}

.wrapper{
  background-color: #ccc;
  width: 500px;
  margin: auto;
  padding: 0;
   display: block;
   background: green;
}

.box{
  display: block;
  margin: 0px;
  width: 248px;
  height: 250px;
  background: red;
  padding: 0;
  float: left;
}

显示:inline-block创建了那个边距。 或者您可以尝试 .wrapper {font-size: 0;} .box {display: inline-block;}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接