Home > database >  How to fit image to parent div with scaling and without stretching
How to fit image to parent div with scaling and without stretching

Time:07-07

I have a div that has a certain fixed width and height. I want to fit inside an image (it's dimensions are previously unknown) without stretching it (keep aspect ratio). Object fit would work but for the sake of image being wrapped inside of another wrapper div (to apply shadow), so it cannot be used this time.

To make it clear: I can't use object-fit, nor making it a background image.

How is this done properly with CSS?

further images to demonstrate my intentions: (blue rectangle on the right represents the original image in its original size, on the left it is how it should display inside it's dashed parent) enter image description here enter image description here enter image description here

CodePudding user response:

If i understood correctly this should do it

object-fit: contain;

CodePudding user response:

.section{
height:90vh;
width:100%;
border: 2px solid black;

}
.img{
height:100%;
width:100%;
background-image: url('https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1239&q=80');
background-position: center;
background-repeat: no-repeat;
background-size: contain;
}
  
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div >
        <div >
            <div ></div>
        </div>
    </div>
</body>
</html>

you can resize the browser and the aspect ration wont change, I hope this is what you are looking for

  • Related