互联网技术 · 2024年2月12日

解决div与div之间的空隙问题

今天在制作页面的时候发现两个div之间有空隙导致两个本来应该在一起的效果,这里结合一下解决方法。

当你使用HTML div块与块的中间不能紧密连接 怎么都解决不了时

1、可以在中间内容里加一个

* {

margin:0;

padding:0;

}

2、上下div之间有间距的问题

我写了4个div,上下分布,均存在间距,代码以及效果如下:

.div1{
height:100px;
background-color:blue;
position:relative;
}
.div2 {
height:100px;
background-color:blueviolet;
position:relative;
}
.div3{
height:100px;
background-color:red;
position:relative;
}
.div4{
height:100px;
background-color:yellow;
position:relative;
}

div与div之间有空隙的解决方法

然后,我尝试在每个div中加margin:0来去掉div之间的间距,代码如下:

.div1{

height:100px;

background-color:blue;

position:relative;

margin: 0;

}

.div2 {

height:100px;

background-color:blueviolet;

position:relative;

margin: 0;

}

.div3{

height:100px;

background-color:red;

position:relative;

margin: 0;

}

.div4{

height:100px;

background-color:yellow;

position:relative;

margin: 0;

}

结果效果不变,依然有间隙,如下图:

div与div之间有空隙的解决方法

接下来我进行了百度,找到了一个方法,设置font-size,如下代码以及效果:

body{font-size:0;}

.div1{

height:100px;

background-color:blue;

position:relative;

}

.div2 {

height:100px;

background-color:blueviolet;

position:relative;

}

.div3{

height:100px;

background-color:red;

position:relative;

}

.div4{

height:100px;

background-color:yellow;

position:relative;

}

上面代码重点添加了body{font-size:0;},其效果如下:

div与div之间有空隙的解决方法

可以看到div上下之间的间隙消除了.然而,最上面和最左面依然有间隙.

对此,我是这么做的,添加了body{margin:0px;},代码如下:

body{margin:0px;}

body{font-size:0;}

.div1{

height:100px;

background-color:blue;

position:relative;

}

.div2 {

height:100px;

background-color:blueviolet;

position:relative;

}

.div3{

height:100px;

background-color:red;

position:relative;

}

.div4{

height:100px;

background-color:yellow;

position:relative;

}

效果如下:

div与div之间有空隙的解决方法

可以看到,间距全部消除了.

然而,还存在一个问题,就是由于设置了font-size:0;.那么会导致所有的字体消失.

对此,我是这么解决的:在div中在添加div,重新设置内div的字体大小,比如:font-size:30px;.

完美解决!

3、DIV+CSS clear:both清除产生浮动后,会在div上方产生空隙的问题

我们知道有时使用了css float浮动会产生css浮动,这个时候就需要清理清除浮动,我们就用clear样式属性即可实现。

但是在使用了clear:both清除产生的浮动后,往往会在这个应用了clear:both的div的上方出现一个白色空隙。

解决办法是在这个div的上方的div加上overflow:hidden;

北京

样式说明:

.cle{clear:both;}
.hid{overflow:hidden;}
.fl{ float:left;}
.fr{ float:right;}

这是这几天解决clear:both所产生div空隙的办法。

为什么要在div中使用clear:both?主要是因为div b中的文字即使在css中设置了text-align:left; 文字也无法居左,所以这种情况下使用了clear:both。

几个问题:

(1)为什么div中文字的text-align:left;无效?

(2)为什么text-align:left;无效的情况下,使用clear:both可以解决?

(3)为什么使用clear:both会产生空隙?

(4)为什么在上方的同级div中,使用overflow:hidden;会解决下方出现的空隙问题?

以上这些问题,以后有机会再具体研究一下吧。

总结:

当div应用clear:both 产生空隙后,需要在其上方的同级div加上overflow:hidden;,即可消除空隙。

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.