繁体   English   中英

如何防止使用 CSS 缩放背景图像?

[英]How to prevent scaling of background image using CSS?

我有一个高分辨率图像,它是 div 的背景图像。 div 一直以较小的尺寸呈现它,但我想保持它不缩放。 我不介意裁剪背景图像以仅显示图像的一部分,只要该部分具有原始大小即可。

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;
}

您可以指定以下 CSS 属性

background-size: cover;

这将确保背景覆盖整个元素,无论它是否被裁剪,不同的是

background-size: contain;

这将缩放图像以适合元素并完全可见

如果您想通过使用background-size: cover来防止缩放。 这会裁剪背景,对我来说永远不会延伸。

关于background-size更多信息: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

暂无
暂无

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

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