我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。
我无法预测图像的纵横比,所以没有办法知道是否使用:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。
<div>的大小由屏幕的百分比设置,这也是不可预测的。
我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。
我无法预测图像的纵横比,所以没有办法知道是否使用:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。
<div>的大小由屏幕的百分比设置,这也是不可预测的。
当前回答
如果你能够将图像设置为背景图像,那么你可以这样做,这将裁剪图像而不拉伸它:
<div style="background-image: url(...); background-size: cover; width: 100%; height: 100%;"></div>
如果你需要坚持使用<img>标签,那么从2019年开始,你现在可以使用对象适合css属性,它接受以下值: 填充|包含|覆盖|无|缩小
参见https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
举个例子,你可以有一个存放图像的容器:
<div class="container">
<img src="" class="container_img" />
</div>
.container {
height: 50px;
width: 50%;
}
.container_img {
height: 100%;
width: 100%;
object-fit: cover;
}
其他回答
HTML:
<style>
#foo, #bar{
width: 50px; /* use any width or height */
height: 50px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">
JSFiddle
...如果你想设置或改变图像(以#foo为例):
jQuery:
$("#foo").css("background-image", "url('path/to/image.png')");
JavaScript:
document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";
这招对我很管用
div img {
width: 100%;
min-height: 500px;
width: 100vw;
height: 100vh;
object-fit: cover;
}
你可以用object-fit: cover;在父div上。
https://css-tricks.com/almanac/properties/o/object-fit/
如果你使用IMG标签,这很简单。
我做了这个:
<style>
#pic{
height: 400px;
width: 400px;
}
#pic img{
height: 225px;
position: relative;
margin: 0 auto;
}
</style>
<div id="pic"><img src="images/menu.png"></div>
$(document).ready(function(){
$('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
)}
但我不知道如何使它与#pic {background:url(img/menu.png)}一起工作 Enyone吗? 谢谢
使用这种方法,你可以在div中填充不同比例的div和图片。
jQuery:
$(window).load(function(){
$('body').find(.fillme).each(function(){
var fillmeval = $(this).width()/$(this).height();
var imgval = $this.children('img').width()/$this.children('img').height();
var imgClass;
if(imgval > fillmeval){
imgClass = "stretchy";
}else{
imgClass = "stretchx";
}
$(this).children('img').addClass(imgClass);
});
});
HTML:
<div class="fillme">
<img src="../images/myimg.jpg" />
</div>
CSS:
.fillme{
overflow:hidden;
}
.fillme img.stretchx{
height:auto;
width:100%;
}
.fillme img.stretchy{
height:100%;
width:auto;
}