我将背景图片设置为contain
:
.el {
background: url(path/to/img.jpg) no-repeat center center;
background-size: contain;
}
但是这会将图像放大。我希望图像永远不会比其本机尺寸大,并且只有在其本机分辨率下无法适合时才会缩小。
这里是一个演示:http://jsfiddle.net/6W3yh/
我只想用CSS解决方案。
请不要使用JavaScript。
我将背景图片设置为contain
:
.el {
background: url(path/to/img.jpg) no-repeat center center;
background-size: contain;
}
但是这会将图像放大。我希望图像永远不会比其本机尺寸大,并且只有在其本机分辨率下无法适合时才会缩小。
这里是一个演示:http://jsfiddle.net/6W3yh/
我只想用CSS解决方案。
请不要使用JavaScript。
很遗憾,CSS无法实现您想要的功能。
最好的方法是使用JavaScript设置背景大小。 但是,如果您希望图像在容器小于其大小时缩小,则必须能够获取图像的自然高度。
if ($('.el').height() < imageHeight) {
$('.el').css('background-size', 'contain');
}
else {
$('.el').css('background-size', 'auto');
}
background-size
属性没有解决这个问题? - MegaHitdiv {
background: url(http://cdn4.iconfinder.com/data/icons/silent_night_icons/128/santa.png) no-repeat center center;
background-size: 100%;
width: 100%;
max-width: 128px;
height: 0;
padding-bottom: 100%; /* (Image Height / Image Width) * 100%; */
}
这个方法在浏览器上有很好的支持:https://caniuse.com/#feat=object-fit
.container {
position: relative;
width: 200px;
height: 200px;
/* Just for style */
display: inline-block;
background: rgba(0,0,0,0.2);
margin: 10px;
}
.container img {
width: 100%;
height: 100%;
object-fit: scale-down;
}
<div class="container">
<img src="https://picsum.photos/300/200">
</div>
<div class="container">
<img src="https://picsum.photos/200/300">
</div>
<div class="container">
<img src="https://picsum.photos/100/100">
</div>
当您需要针对旧版浏览器进行目标定位时,无需更改标记即可同样有效。
.container {
position: relative;
width: 200px;
height: 200px;
/* Just for style */
display: inline-block;
background: rgba(0,0,0,0.2);
margin: 10px;
}
.container img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 100%;
max-height: 100%;
}
<div class="container">
<img src="https://picsum.photos/300/200">
</div>
<div class="container">
<img src="https://picsum.photos/200/300">
</div>
<div class="container">
<img src="https://picsum.photos/100/100">
</div>
$('.target').each(function() {
if ($(this).css('background-size') == 'contain') {
var img = new Image;
var currObj = $(this);
img.src = currObj.css('background-image').replace(/url\(|\)$/ig, "").replace(/"/g, "").replace(/'/g, "");
img.onload = function(){
if (img.width < currObj.width() && img.height < currObj.height()) {
currObj.css('background-size', 'auto auto');
}
}
}
});
<div></div>
<img id="background" style="display: none" src="http://cdn4.iconfinder.com/data/icons/silent_night_icons/128/santa.png" />
JS:
var backgroundSize = $('#background').css('width');
CSS解决方案:您需要知道图像的高度和宽度。
@media screen and (max-width: 640px) and (max-height: 480px) {
div {
background-size: contain !important;
}
}
div {
background: #000 url('https://i.imgur.com/someimage.jpg') no-repeat center center;
background-size: 640px 480px;
}
图片的URL为https://i.imgur.com/someimage.jpg
,宽度和高度分别为640px
和480px
。