简体   繁体   English

拉伸图像以适合Div高度和宽度的100%

[英]Stretch Image to Fit 100% of Div Height and Width

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. 无论实际图像的分辨率如何,我都希望我的网络图像始终保持相同的尺寸(以1:1的比例)。 If my actual image files are square (with 1:1 ratio) then this isn't a problem. 如果我的实际图像文件是正方形(比例为1:1),那么这不是问题。 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). 但是,如果实际的图像文件不是方形的,则显示的Web图像确实会拉伸到div的高度和宽度的100%(在这种情况下为200px)。

How do I get different image sizes to fit to my DIV? 如何获得不同的图像尺寸以适合DIV?

You're mixing notations. 您正在混合符号。 It should be: 它应该是:

<img src="folder/file.jpg" width="200" height="200">

(note, no px ). (请注意,没有px )。 Or: 要么:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) 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%;
}

Instead of setting absolute widths and heights, you can use percentages: 您可以使用百分比来代替设置绝对宽度和高度:

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

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>

will the height attribute stretch the image beyond its native resolution? height属性是否会将图像拉伸到超出其原始分辨率? 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即将接近,由于某种原因,底部仅剩几个像素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM