CSS使用display:inline-block会产生的问题以及解决的方法

  • Post author:
  • Post category:其他



问题复现


问题: 两个


display:inline-block


元素放到一起会产生一段空白。


如代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<style>
			.container {
				width: 800px;
				height: 200px;
			}
			
			.left {
				font-size: 14px;
				background: #bfa;
				display: inline-block;
				width: 100px;
				height: 100px;
			}
			
			.right {
				font-size: 14px;
				background: #f0f;
				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

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

(3)为子元素设置

float:left

(right也是同理)

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



版权声明:本文为weixin_48005981原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。