为什么两个行内块元素(内联元素)之间有空格

如题,这是学习前期经常遇到的问题,所以就来讲讲为什么,怎么办。

为什么

首先先做一个 demo 出来,看问题是否存在。

<div class="father">
    <div class="son1"></div>
    <div class="son2"></div>
</div>
.father {
    width: 200px;
    height: 50px;
    border: 1px solid red;
}
        
.son1 {
    display: inline-block;
    width: 50px;
    height: 50px;
    background-color: #652373;
}
        
.son2 {
    display: inline-block;
    width: 50px;
    height: 50px;
    background-color: #74BF75;
}

果然,中间有一道缝隙哈,现在我们来看看为什么。

用 JS 打印打印 father 盒子的所有子元素看看。

<script>
    let father = document.querySelector('.father');
    console.log(father.childNodes);
</script>

 再看看这个 text 究竟是啥。

没错,它竟然是两个子 div 之间的换行+后面的一系列空格。。。

这也是 HTML 自身的特性了。

解决方案:

1.float:left

这是我最推荐的方式。

缺点是没有缺点!

如代码所示,给两个子元素加上浮动。

注意,这里就要把两个子元素中 display:inline-block 的语句删掉了,float 属性中就带有这个效果。

.son1 {
    float: left;
    width: 50px;
    height: 50px;
    background-color: #652373;
}
        
.son2 {
    float: left;
    width: 50px;
    height: 50px;
    background-color: #74BF75;
}

 客户说效果很好,腿都不酸了。

2.把代码写在一行

<div class="father">
    <div class="son1"></div><div class="son2"></div>
</div>

效果同样,可以实现,但是正常人都不习惯这么写。

3.把中间的文本注释掉

<div class="father">
    <div class="son1"></div><!--
    --><div class="son2"></div>
</div>

我想正常人更不会这么写了。。

但是效果还是杠杠的。

4. 将父元素的 font-size 属性设置为0

.father {
    width: 200px;
    height: 50px;
    border: 1px solid red;
    font-size: 0;
}

做的很好,下次不许再这么做了。。

因为通常元素中都是由文字的。你把字的大小设置为0,虽然没有缝隙了,但是其他字也显示不了了。

总结

第一种,浮动是最好的。

第二三钟,不加空格或者把空格注释掉,会破坏代码的可读性和优美。

第四种,将父元素的字大小设置为0,不推荐使用。

猜你喜欢

转载自blog.csdn.net/Cristiano2000/article/details/122504228