当浏览器宽度更改时,css 缩放背景图像



我有以下html和css

.image-container {
background-image: url('https://i.stack.imgur.com/GA6bB.png');
background-size: cover;
background-repeat: no-repeat;
background-position: 50% 50%;
width: 100%;
height: 450px;
}
<div class="image-container"></div>

上面显示了图像,但没有响应。调整页面大小时,图像会丢失某些区域。调整浏览器大小时如何维护图像

使用contain

.image-container {
background-image: url('https://i.stack.imgur.com/GA6bB.png');
background-size: contain;
background-repeat: no-repeat;
background-position: 50% 50%;
width:100%;
height:450px;
}
<div class="image-container"></div>

来自 MDN:

contain:在不裁剪或拉伸图像的情况下尽可能大地缩放图像。

我希望这段代码能解决你的问题:

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.aspect-ratio-container {
position: relative;
height: 0;
padding-top: 56.25%;
}
.aspect-ratio-container .aspect-ratio-item {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-image: url('https://i.stack.imgur.com/GA6bB.png');
background-repeat:no-repeat;
background-size:cover;
background-position: center center
}

</style>
</head>
<body>
<div class="aspect-ratio-container">
<div class="aspect-ratio-item"></div>
</div>
</body>
</html>

使用包含:


<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.image-container {
background-image: url('https://i.stack.imgur.com/GA6bB.png');
background-size:contain;
background-repeat:no-repeat;
background-position: 50% 50%;
width:100%;
height:450px;
}  
</style>
</head>
<body>
<div class="image-container"></div>

</body>
</html>

最新更新