问题描述
在网页中插入图片,图片不受父元素的限制,总共分为两种情况:
- 如果父元素是块级元素,插入的图片会把父元素的高度撑开,并与父元素的底边框留下空隙
- 如果父元素是行内元素,插入的图片会把父元素的宽度撑开,并与父元素的底边框留下空隙
情景再现
<!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>image</title>
<style>
div {
width: 300px;
border: 5px solid red;
}
img {
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<div>
<img src="../images/shenzhen.jpg" alt="123">
</div>
</body>
</html>
页面效果:
<!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>image</title>
<style>
span {
border: 1px solid red ;
}
img {
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<span>
<img src="../images/shenzhen.jpg" alt="lalal">
</span>
</body>
</html>
页面效果:
默认情况下,图片与父级元素的下边框存在一个空隙,这是图片的特征,也是行内元素的一个特性。
解决方法
- 设置父元素的高度等于图片的高度
- 给<img>标签添加vertical-align垂直对齐属性,可取值为top,middle,bottom
!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>image</title>
<style>
span {
border: 1px solid red ;
}
img {
width: 400px;
height: 300px;
vertical-align: top;
}
</style>
</head>
<body>
<span>
<img src="../images/shenzhen.jpg" alt="lalal">
</span>
</body>
</html>
页面效果:
<!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>image</title>
<style>
div {
width: 300px;
border: 5px solid red;
height: 300px;
}
img {
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<div>
<img src="../images/shenzhen.jpg" alt="lalal">
</div>
</body>
</html>
页面效果: