小言_互联网的博客

display:inline-block在使用时产生空白的原因及解决方法

176人阅读  评论(0)

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .container{
            width:800px;
            height:200px;
        }
        .left{
            font-size:14px;
            background:red;
            display: inline-block;
            width:100px;
            height:100px;
        }
        .right{
            font-size:14px;
            background:blue;
            display: inline-block;
            width:100px;
            height:100px;
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="left"></div>
        <div class="right"></div>
    </div>
</body>
</html>

效果

原因
元素被当成行内元素排版的时候,元素之间的空白符(空格、回车换行等)都会被浏览器处理,根据CSS中white-space属性的处理方式(默认是normal,合并多余空白),原来HTML代码中的回车换行被转成一个空白符,在字体不为0的情况下,空白符占据一定宽度,所以inline-block的元素之间就出现了空隙。

解决
1.将子元素标签的结束符和下一个标签的开始符写在同一行或把所有子标签写在同一行

<div class="container">
        <div class="left"></div><div class="right"></div>
</div>

2.父元素中设置font-size: 0,在子元素上重置正确的font-size,注意inline-block元素必须设定字体,不然行内元素中的字体不会显示。

 .container{
            width:800px;
            height:200px;
            font-size:0;
        }

3.设置父元素,display:table和word-spacing设置为负值,可以兼容chrome,Firefox,edge,opera浏览器

 .container{
            width:800px;
            height:200px;
            display: table;
            word-spacing: -1em;
        }

4.为子元素设置float:left

	 .left{
            float: left;
            font-size:14px;
            background:red;
            display: inline-block;
            width:100px;
            height:100px;
        }
        .right{
            float: left;
            font-size:14px;
            background:blue;
            display: inline-block;
            width:100px;
            height:100px;
        }

转载:https://blog.csdn.net/qq_43393963/article/details/102324438
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场