CSS Width and Height of the Image Image

I am trying to make an image fit its container. The problem is that I can only set it for width width: 100%

or height height: 100%

, but not both.

Basically, it should check the length of the container or the height of the container versus the width and height of the image (normalize) and adapt it to that. And it also needs to center the image.

This is the standard behavior in Windows Photo Viewer. The image is always visible, centered and proportional. I am trying to do it this way.

PS: I would prefer a css solution. But if it's not possible / very painful, js is fine too.

PSPS: Sorry if this is a duplicate. I searched the internet and found similar questions, but none of them seemed to have the right answer.

+3


source to share


2 answers


You can set the image using CSS background-image

, for example:

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/

0


source


There are several solutions. None of them are perfect. And it usually depends on whether you want to crop the image or not.

If you're ok 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 be cropped, it will depend on how you want to lay out the image (or images). Here are some examples:

+1


source







All Articles