【问题标题】:How to remove white spaces around img tag? [duplicate]如何删除img标签周围的空格? [复制]
【发布时间】:2022-02-19 01:46:08
【问题描述】:

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

代码如下:

<!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>

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

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    您可以像这样在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;
     }
    

    这是因为默认情况下,imginline 元素,这意味着通过CSS 设置的widthheigh 将不起作用。在父级上有一个display : flex,使img 成为一个弹性元素,女巫的行为类似于block 元素。

    【讨论】:

    • 好的,但我只能在 6 分钟后这样做,所以在那之后我一定会这样做:)
    【解决方案2】:

    img 是一个内联元素。这意味着您无法设置其宽度或高度。为此,您首先需要使其成为块或内联块元素,或者您可以只使用 display flex 并且 img 现在将成为 flex-items。空白是由于 p 标签的边距

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

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

    display: inline-block;
    width: 50%; 
    

    在 p 和 img 标签中。显示:弯曲;也很棒。

    【讨论】: