简体   繁体   中英

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.

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. 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. But if it is impossible/very painful, js is also ok.

PSPS: Sorry if this is a duplicate. 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:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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