我需要使这张图像拉伸到最大尺寸,而不溢出它的<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>的大小由屏幕的百分比设置,这也是不可预测的。
当前回答
你可以用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吗? 谢谢
我在寻找一个类似的问题时遇到了这个问题。我正在制作一个响应式设计的网页,页面上放置的元素的宽度设置为屏幕宽度的百分比。高度用vw值设置。
因为我用PHP和数据库后端添加了帖子,纯CSS是不可能的。然而,我确实发现jQuery/javascript的解决方案有点麻烦,所以我想出了一个整洁的解决方案(至少我是这么认为的)。
HTML (php)
div.imgfill { float: left; position: relative; background-repeat: no-repeat; background-position: 50% 50%; background-size: cover; width: 33.333%; height: 18vw; border: 1px solid black; /*frame of the image*/ margin: -1px; } <div class="imgfill" style="background-image:url(source/image.jpg);"> This might be some info </div> <div class="imgfill" style="background-image:url(source/image2.jpg);"> This might be some info </div> <div class="imgfill" style="background-image:url(source/image3.jpg);"> This might be some info </div>
通过使用style="",可以让PHP动态更新我的页面,css样式和style=""将最终在一个完美覆盖的图像中结束,缩放以覆盖动态div标签。
我也有类似的问题。我只用CSS解决了这个问题。
基本上,Object-fit: cover可以帮助你实现在div中定位图像时保持纵横比的任务。
但问题是物体匹配:封面在IE中无法工作,它采用100%的宽度和100%的高度,纵横比扭曲。换句话说,我在chrome浏览器中看到的图像缩放效果没有了。
我采用的方法是在容器中使用absolute定位图像,然后使用组合将其放在正中央:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
一旦它在中心,我给图像,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
这使得图像得到对象适合:覆盖的效果。
下面是上述逻辑的演示。
https://jsfiddle.net/furqan_694/s3xLe1gp/
这种逻辑适用于所有浏览器。
这招对我很管用
div img {
width: 100%;
min-height: 500px;
width: 100vw;
height: 100vh;
object-fit: cover;
}
使用这种方法,你可以在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;
}