Html 图像扩展大于父 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25630915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:38:11  来源:igfitidea点击:

Image expanding larger than parent div

htmlcss

提问by user3167249

I have a div that contains an image. I want the image to resize with the div, but I do not want the image to ever have a height greater than 480px. I will post what I have below. It resizes with the div correctly, but it does not obey the max-height. If I move the mx height to the img css it does, but it will not resize then. I'm sure its something simple, but I can't seem to get it.

我有一个包含图像的 div。我希望图像与 div 一起调整大小,但我不希望图像的高度大于 480 像素。我会在下面发布我所拥有的。它正确地随 div 调整大小,但不遵守最大高度。如果我将 mx 高度移动到 img css,但它不会调整大小。我确定它很简单,但我似乎无法理解。

.feature_image {    
    max-height:480px
}

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

And here is the HTML

这是 HTML

<div class="feature_image">
        <img src="img/main-featured-image.png"/>
    </div>

回答by Cowwando

You need to specify not only max-height; but also height in order to use height 100% for the image! :) CSS has no idea what 100% of to inherit. I hope you get it.

您不仅需要指定 max-height;还要高度以使用高度 100% 作为图像!:) CSS 不知道什么是 100% 的继承。我希望你能明白。

.feature_image {    
    max-height:480px;
    height: 480px;
}

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

回答by Johnny

Have you tried putting a display:block?

你试过放一个display:block吗?

Full CSS would look like:

完整的 CSS 看起来像:

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

回答by Billal Begueradj

The reason behind your issue is that you did not specify the widthof the container but, in the same time, you set a width: 100%;for the image.

问题背后的原因是您没有指定width容器的 ,但同时width: 100%;为图像设置了。

I tested this with and it works just fine:

我对此进行了测试,效果很好:

.feature_image {    
    height: 480px;
    width: 480px;
}

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

This solution is good for small images, however it causes large images to distort, but there are solutions to overcome it.

此解决方案适用于小图像,但会导致大图像失真,但有解决方案可以克服它

回答by Mihai

You need width:auto;

你需要宽度:自动;

.feature_image img{

    max-height:480px;
    width: auto;
}

http://jsfiddle.net/8qLeE/51/

http://jsfiddle.net/8qLeE/51/