背景:
在练习flex布局时无意间发现img元素与同级div元素之间存在间隙,网上虽然有解决方法,但是却不知道为什么这么做,在这里记录下我的观点。
原因
代码示例:
<header>
<img class="profile-thumbnail" src="https://freecodecamp.s3.amazonaws.com/quincy-twitter-photo.jpg" alt="Quincy Larson's profile picture">
<div class="profile-name">
<h3>Quincy Larson</h3>
<h4>@ossia</h4>
</div>
<div class="follow-btn">
<button>Follow</button>
</div>
</header>
body {
font-family: Arial, sans-serif;
}
header {
/*display: flex;*/
background: bisque;
}
header .profile-thumbnail {
width: 50px;
height: 50px;
border-radius: 4px;
background: #477ca7;
/*display: block;*/
}
header .profile-name {
margin-left: 10px;
background: #74638f;
}
header h3, header h4 {
margin: 0;
}
header .follow-btn {
margin: 0 0 0 auto;
background: coral;
}
header .follow-btn button {
border: 0;
border-radius: 3px;
padding: 5px;
}
可以看到头像与下面的名字之间存在间隙,原因是 img
元素的 display
属性默认是 inline-block
类型,即 img
可以使用 block
类型独有的 width
和 height
,但是在布局时它却有 inline
的属性,多个 img
元素可以在一行。
通过观察html代码可以发现img与下面 相邻的div之间存在空格,即inline-block布局的元素在编辑器里不在同一行,存在换行符,因此这就是著名的inline-block“换行 符/空格间隙问题”。如果inline-block元素间有空格或是换行产生了间隙,那是正常的。
解决方法
- 将img的display属性设置为block
img { display: block; }
- 修改img的vertical-align属性:
img{vertical-align:buttom;} img{vertical-align:middle;} img{vertical-align:top;}
- 将父级element中的字体大小设为0,同级div中字体打下分别重新设置:
div{font-size:0;}
参考
Is img element block level or inline level?
How do I remove the space between inline-block elements?
解决div和img之间的空隙