Html 拉伸图像以适应 100% 的 Div 高度和宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16501668/
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
Stretch Image to Fit 100% of Div Height and Width
提问by Lloyd Banks
I have a div with the following CSS
我有一个带有以下 CSS 的 div
#mydiv{
top: 50px;
left: 50px;
width: 200px;
height: 200px;
}
and my HTML looks like this
我的 HTML 看起来像这样
<div id = "mydiv">
<img src = "folder/file.jpg" width = "200px" height = "200px">
</div>
I'd like my web image to always be the same size (in a 1:1 aspect ration) no matter what the resolution of the actual image is. If my actual image files are square (with 1:1 ratio) then this isn't a problem. But if the actual image files are not square then the displayed web image do stretch to 100% of both the div's height and width (in this case 200px).
无论实际图像的分辨率如何,我都希望我的网络图像始终具有相同的大小(以 1:1 的纵横比)。如果我的实际图像文件是方形的(比例为 1:1),那么这不是问题。但是,如果实际图像文件不是正方形,则显示的 Web 图像确实会拉伸到 div 高度和宽度的 100%(在本例中为 200 像素)。
How do I get different image sizes to fit to my DIV?
如何获得不同的图像大小以适合我的 DIV?
采纳答案by bfavaretto
You're mixing notations. It should be:
你在混合符号。它应该是:
<img src="folder/file.jpg" width="200" height="200">
(note, no px). Or:
(注意,没有px)。或者:
<img src="folder/file.jpg" style="width: 200px; height: 200px;">
(using the styleattribute) The style attribute could be replaced with the following CSS:
(使用style属性)可以用以下 CSS 替换 style 属性:
#mydiv img {
width: 200px;
height: 200px;
}
or
或者
#mydiv img {
width: 100%;
height: 100%;
}
回答by dodgerogers747
Instead of setting absolute widths and heights, you can use percentages:
您可以使用百分比,而不是设置绝对宽度和高度:
#mydiv img {
height: 100%;
width: 100%;
}
回答by Haze811
Or you can put in the CSS,
或者你可以放入 CSS,
<style>
div#img {
background-image: url(“file.png");
color:yellow (this part doesn't matter;
height:100%;
width:100%;
}
</style>
回答by Jerritt Pace
will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.
高度属性是否会将图像拉伸到超出其原始分辨率?如果我有一个高度为 420 像素的图像,我无法让 css 将图像拉伸到超出原始分辨率以填充视口的高度。
I am getting pretty close results with:
我得到了非常接近的结果:
.rightdiv img {
max-width: 25vw;
min-height: 100vh;
}
the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.
100vh 已经非常接近了,由于某种原因,底部只剩下几个像素。