简体   繁体   中英

How to prevent scaling of background image using CSS?

I have a high-resolution image that is the background image of a div. The div keeps rendering it at a smaller size but I would like to leave it unscaled. I don't mind that the background image is cropped to show only a portion of the image as long as that portion has the original size.

Javascript:

console.log(img.width) // this comes out 3840px
resultDiv.style.backgroundImage = "url('" + img.src + "')"; 
resultDiv.style.backgroundRepeat = "no-repeat";

CSS:

.img-full {//this is the class of the img

    max-width: none;
    max-height: none;
}

#bottomPanel {//this is the resultDiv that is scaling the background image

    height: 30vh;
    background: black;
    margin-left: 10px;
    margin-right: 10px;
    overflow-x: auto;
    overflow-y: auto;
}

you can specify the following CSS Property

background-size: cover;

this will make sure the background covers the whole element regardless if it was cropped or not, different that

background-size: contain;

that will scale the image to be fit within the element and to be fully visible

If you would like to prevent scaling by using background-size: cover . This crops the background, and it never stretches for me.

More info about background-size : https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

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