简体   繁体   English

CSS 图像适合宽度和高度

[英]CSS Image fit width and height

I am trying to make an image fit to its container.我正在尝试使图像适合其容器。 The problem is, that I can only set it to fit to the width width: 100% or the height height: 100% but not both.问题是,我只能将它设置为适合宽度width: 100%或 height height: 100%但不能同时设置。

Basically it should check weather container length or height is smaller compared to image width and height (normalized) and adapt it to that.基本上它应该检查天气容器的长度或高度与图像宽度和高度(标准化)相比是否更小,并对其进行调整。 And it should also center the image.它也应该使图像居中。

This is standard behavior in Windows Photo Viewer.这是 Windows 照片查看器中的标准行为。 The image is always visible, centered and preservers the ratio.图像始终可见,居中并保持比例。 I am trying to make it exactly like that.我正在努力使它完全像那样。

PS: I would prefer a css solution. PS:我更喜欢 css 解决方案。 But if it is impossible/very painful, js is also ok.但是如果不可能/很痛苦,js也可以。

PSPS: Sorry if this is a duplicate. PSPS:对不起,如果这是重复的。 I searched the internet and found similar questions, but none of them seemed to had the right answer.我在互联网上搜索并发现了类似的问题,但似乎没有一个有正确的答案。

There are a few solutions to this.对此有几种解决方案。 None of them perfect.他们没有一个是完美的。 And it usually depends if you want the image to be cropped or not.这通常取决于您是否想要裁剪图像。

If you're fine with cropping you can try something like:如果您对裁剪没问题,可以尝试以下操作:

<div class="image"></div>
<style>
    .image {
          width:250px;
          height:150px;
          background-image:url('http://lorempixel.com/400/200/');
          background-size:cover;
    }
</style>

If you don't want it to crop then it will depend how you want to lay out the image (or images).如果您不希望它被裁剪,那么它将取决于您想要如何布置图像(或图像)。 Here are a couple of examples:下面是几个例子:

You can set image with CSS background-image , like this:您可以使用 CSS background-image设置图像,如下所示:

div{
    width: 200px;
    height: 200px;
    background-image: url("http://i.imgur.com/cjgKmvp.jpg");
    background-size: contain;
    background-repeat: no-repeat;
}

DEMO: https://jsfiddle.net/ue49awaL/8/演示: https : //jsfiddle.net/ue49awaL/8/

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

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