[CSS]inline-block的元素空隙问题多种方案解决

2022-05-06 445点热度 0人点赞 0条评论

问题描述

我们使用到给元素设置成display:inline-block; 例如用于同一行摆放多个元素,发现一个问题,他们之间有空隙,如下所示代码:

<div style="padding: 0px;margin:0px;">
    <div style="display:inline-block;background:red;width:50px;height:50px;"></div>
    <div style="display:inline-block;background:green;width:50px;height:50px;"></div>
    <div style="display:inline-block;background:yellow;width:50px;height:50px;"></div>
</div>

会发现,两个元素之间都会产生空隙(尽管已经设置了padding:0px;margin:0px),如上图。

解决办法

  • 方案1

两个元素之间不要增加空行,猜测可能是空行换行之类的引起的,因为改成如下就可以了:

<div style="paddding:0px;margin:0px;">
    <div style="display:inline-block;background:red;width:50px;height:50px;"></div><div
    style="display:inline-block;background:green;width:50px;height:50px;"></div><div
    style="display:inline-block;background:yellow;width:50px;height:50px;"></div>
</div>

只要在第二个div结束的时候,立即开始下一个div,会发现空白消失了,这样能解决问题,但是代码上会有点不美观。

  • 方案2

如果里面的元素不需要放置文字text,那么可以把字体设置为:font-size: 0px; (当然如果要使用文本,可以在div里面再套其他的标签,给文字大小设置为正常的font-size)

<div style="paddding:0px;margin:0px;font-size:0px;">
    <div style="display:inline-block;background:red;width:50px;height:50px;"></div>
    <div style="display:inline-block;background:green;width:50px;height:50px;"></div>
    <div style="display:inline-block;background:yellow;width:50px;height:50px;"></div>
</div>
  • 方案3

使用flex布局,如下代码,给最外层设置display:flex;

<div style="display: flex;">
    <div style="background:red;width:50px;height:50px;"></div>
    <div style="background:green;width:50px;height:50px;"></div>
    <div style="background:yellow;width:50px;height:50px;"></div>
</div>

最终如下效果:

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论