如何删除 img 标签周围的空格?

How to remove white spaces around img tag?

我不明白,为什么我要使用 display: flex; 来拉伸整个图像 space。即使我将 img 标签及其父标签 (.hey) 的高度设置为 100%,它也不会工作并且会有白色 space.

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>

        body {
            background-color: bisque;
        }
        .wrapper {
            display: flex;
            flex-direction: row;
        }

        img {
            width: 100%;
            height: 100%;
        }

        .hey {
            /* If we won't place display: flex; the image height won't be affected and white space would occur */
            /* display: flex; */
            height: 100%;
        }

        .dance {
            background-color: aqua;
        }

        @media screen and (max-width: 768px) {
            .wrapper {
                flex-direction: column;
            }
        }
    </style>
    <title>Document</title>
</head>

<body>
    <div class="wrapper">
        <div class="hey"><img src="./img/blog/blog2.jpg" alt=""></div>
        <div class="dance">
            <h4>Hey</h4>
            <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sapiente rerum aliquid tempora ipsum facere
                neque, sint expedita nihil laboriosam accusantium.</p>
        </div>
    </div>
</body>

</html>

你能解释一下为什么会这样吗?

您可以像这样在 img 上简单地添加一个 display : block :

 img {
      display:block;
      /* 
         the lines below is for when you want the image 
         fills its parent also vertically 
         whiteout loosing quality
      */
      height: 100%;
      object-fit:cover;
 }

这是因为默认情况下,img 是一个 inline 元素, 表示 widthheigh 通过 CSS 设置不会工作。在父级上有一个 display : flex,使 img 成为一个 flex 元素, 在某个点上表现得像 block 元素。

img 是一个行内元素。这意味着您不能设置它的宽度或高度。为此,您首先需要使其成为块或内联块元素,或者您可以只使用 display flex 并且 img 现在将成为弹性项目。白色 space 是由于 p 标签的边距

img {
  display: block;
  width: 100%;
  height: 100%;
}

如上一个回答中所建议,您可以使用此代码,但它仍然无法工作,因为您仍然需要为 p 标签腾出空间。你需要先想想你真正想要的是什么。如果您希望将您的 p 标签放在 img 上,请在此站点上搜索,我们会向您提出大量问题。如果要将它们从左到右对齐,请使用

display: inline-block;
width: 50%; 

在 p 和 img 标签中。显示:弹性;也很棒