Why is there blank space at the bottom of the <img> element?

1 Overview

In modern browsers, there is a blank at the bottom of the <img> element by default, so where does this blank come from?
Is there a better way to remove this blank?

2 Why is there this gap

To understand this problem, we must first understand what CSS means for the vertical-align values ​​of the display: inline element. The default value of vertical-align is baseline, which is a concept that only exists in western typesetting:
Insert picture description here
you can see that the tails under these letters are p, q, and g that appear below the baseline.
Compare the other two common values ​​of vertical-align, top and bottom:
Insert picture description here
you can see that there is a certain distance between baseline and bottom. In fact, the blank space below the inline picture is the distance between the baseline and the bottom. Even if there are only pictures without text, this blank space will exist as long as it is an inline picture.

It is more obvious here. The most direct way to remove this blank is to set the vertical-align of the picture to another value. If there is mixed text in the same line, it should be better to use bottom or middle.

In addition, the value between top and bottom is line-height. If the line-height is set to 0, the distance between the baseline and the bottom will also become 0, and the blank will disappear. If line-height is not set, the default value of line-height is based on font-size, depending on the rendering engine, but it is generally multiplied by a factor (such as 1.2). Therefore, setting font-size to 0 can achieve the same effect without setting line-height. Of course, the consequence of this is that you can't mix graphics and text.

3 solution

  1. Method one, set img to display: block
  2. Method two, set the vertical-align of img: top/bottom/middle; commonly used
  3. Method three, set the parent element line-height: 0;
  4. Method four, set the parent element font-size: 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>
        div{
     
     
            border: 5px solid #000;
            line-height: 0;  /* 方法三,line-height: 0; */
            font-size: 0;  /* 方法四,font-size: 0; */
        }
        img{
     
     
            display: block;  /* 方法一,设置img为display:block */
        }
        img{
     
     
            vertical-align: bottom;  /* 方法二,设置img的 vertical-align:top/bottom/middle;  */
        } 
    </style>
</head>
<body>
    <div>
        <img src="http://b-ssl.duitang.com/uploads/item/201203/11/20120311132147_vfZv4.jpeg" alt="" srcset="">
    </div>
</body>
</html>

The above blog post is partly from You Yuxi, the big brother of Zhihu, thanks!

Guess you like

Origin blog.csdn.net/qq_41800366/article/details/102753788