如何使图像高度适合父 div 的高度

时间:2021-04-23 08:17:10

标签: html css

我希望图像高度适合父 div 的高度,但图像溢出。我该如何解决?

.image-parent{
    max-height: 50%;
}
img{
    height: 100%;
}
<div class="image-parent">
     <img src="example.jpg" alt="">
</div>

4 个答案:

答案 0 :(得分:0)

需要为容器设置overflow: hidden以防止溢出:

.image-parent {
  max-height: 50%;
  overflow: hidden;
  height: 100px;
}

img {
  max-width: 100%;
  max-height: 100%;
  height: 100%;
  width: 100%;
  object-fit: contain
}

示例:

.image-parent {
    max-height: 50%;
    overflow: hidden;
    height: 100px;
}

img {
    max-width: 100%;
    max-height: 100%;
    height: 100%;
    width: 100%;
    object-fit: contain
}
<div class="image-parent">
     <img src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png" alt="an image">
</div>

答案 1 :(得分:0)

试试这个:

.image-parent{
    max-height: 50%;
}
.image-parent img{
        object-fit:contain;
        height:100%;
}

答案 2 :(得分:0)

你只需要设置一个高度(没有最大值),图像就会自动适应。

工作示例(我添加了您的旧示例以供参考):

p1
.container{ 
    height: 400px;
}
.image-parent{
    height: 50%;
    background-color: grey;
}
.old-image-parent{
    max-height: 50%;
    background-color: #bbb;
}
img{
    height: 100%;
}

答案 3 :(得分:0)

提及 body 的高度并将图像的 max-height 设置为 100%

 html,
    body {
        height: 100%;
    }

    .image-parent {
        height: 50%;
    }

    img {
        max-height: 100%;

    }
<html>
<body>

    <div class="image-parent">
        <img src="https://upload.wikimedia.org/wikipedia/commons/b/b6/Image_created_with_a_mobile_phone.png" alt="">
    </div>

</body>

</html>