Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 当图像小于容器时,CSS使图像适合容器_Html_Css - Fatal编程技术网

Html 当图像小于容器时,CSS使图像适合容器

Html 当图像小于容器时,CSS使图像适合容器,html,css,Html,Css,我有下面的CSS代码,它可以很好地将图像与它的容器相匹配,同时保持图像的大小比 img { /* ASSUMING THE IMAGE IS WIDER THAN 150PX OR HIGHER THAN 100PX */ max-height: 100%; max-width: 100%; } div.mydiv1 { width: 150px; height: 100px; background-color:red; } 但是,如果图像比容器短且窄,

我有下面的CSS代码,它可以很好地将图像与它的容器相匹配,同时保持图像的大小比

img { /* ASSUMING THE IMAGE IS WIDER THAN 150PX OR HIGHER THAN 100PX */
    max-height: 100%;
    max-width: 100%;
}
div.mydiv1 {
    width: 150px;
    height: 100px;
    background-color:red;
}
但是,如果图像比容器短且窄,则它会拉伸以适合(保持大小比)。有办法做到这一点吗


这里有一把小提琴

你不能简单地将宽度设置为100%吗

另外:某些img不可能边对边地放大并适应容器,同时确保其比率保持不变。

这就是您想要的吗?


我认为最接近的方法是将高度或宽度(你想计算它的容器)设置为100%,另一个设置为自动。添加溢出:隐藏;添加到容器将防止图像与其他任何内容重叠。 也就是说:

img {
    max-height: auto;
    width: 100%;
}
div {
    overflow: hidden;
}

看看我的意思。我也同意cpreid的观点,你似乎在问的是不可能的。如果不更改父容器的大小/形状,则不必使用
img
标记。使用css属性
background:url('path/to/img')不重复…
background size:contain

例如在css中

div.mydiv3 {
    width: 300px;
    height: 70px;
    background-color:red;
    background: url("http://cdn-careers.sstatic.net/careers/gethired/img/careers2-ad-header-so-crop.png") no-repeat red;
    background-size: contain;
}
还有HTML

<div class="mydiv3"></div>


我更新了你的小提琴

我不确定我是否理解您的问题,但请尝试使用最小宽度和最小高度为您的图像提供最小大小。

您需要一些javascript来完成此操作

看看这个

Javascript

$("img").each(function(){    
    var real_width = $(this).width();
    var real_height = $(this).height();
    var parentwidth = $(this).parent().width();
    var parentheight = $(this).parent().height();

    var ratioParent = parentwidth / parentheight;
    var ratio = real_width / real_height;    
    var max_width = $(this).css("max-width");
    if (ratioParent < ratio) {        
        $(this).css({width: "100%", height: 'auto'});
    }else{
        $(this).css({width: "auto", height: '100%'});
    }
});
$(“img”).each(function(){
var real_width=$(this).width();
var real_height=$(this).height();
var parentwidth=$(this.parent().width();
var parentheight=$(this.parent().height();
var ratioParent=父宽/父高;
var比率=实际宽度/实际高度;
var max_width=$(this.css(“max width”);
如果(比率<比率){
$(this.css({width:“100%”,height:'auto'});
}否则{
$(this.css({width:'auto',height:'100%});
}
});

元件上使用
对象配合:盖

img { object-fit: cover; }

我喜欢这个答案。我甚至没有想到这一点。主席先生,我以前遇到过这种方法,但最终这将与第三方插件一起使用,因此如果不对插件进行一些修补,可能无法工作。你得到我的投票,因为它确实回答了这个问题!
img { object-fit: cover; }