[CSS]关于<img>标签距离底部盒子5px的问题

发布时间 2023-11-05 14:06:05作者: 夕苜19

 

问题描述:在某个盒子内部放入一个<img>标签,不写样式的情况下,<img>总是和父盒子有5px空隙。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>清除图片多5px问题</title>
        <link rel="stylesheet" type="text/css" href="index.css">
    </head>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .img-container{
            /*设置盒子背景颜色*/
            background-color: lightblue;
        }
        img{
            /*设置图片高度,宽度*/
            height: 700px;
            width: 100%;
        }
    </style>
    <body>
        <div class="img-container">
            <img src="../image/1.jpg" alt="">
        </div>
    </body>
</html>

 

解决方案有4种:

1. 设置父元素 font-size: 0;

    缺点:父元素内如果需要写文字,会有问题。

2. 设置父元素 line-height: 5px;

    缺点:同1。

3. 将 img 元素设置为 vertical-align: bottom;

    缺点:如果父元素display: flex; 则 img 元素中的 vertical-align 属性修改无法生效。

4. 将 img 元素设置为 display: block;

    暂未发现缺点,建议使用。√