如何阻止背景图像在调整大小时收缩




所以我有一个div,背景图像的背景大小设置为覆盖。 这是div 代码:

.imgContainer {
width: 400px;
height: 340px;
z-index: 1;
border: 0;
background: url('https://dummyimage.com/800x680/ccc/333');
background-position: 50% 25%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
border-radius: .25rem;
}
@media screen and (max-width:650px) {
.imgContainer {
width: 100% !important;
}
}
<div class="imgContainer"></div>

背景完全显示了图像,但由于我使我的网站响应,因此我使用 @media 规则更改宽度 650px 上的div。

@media screen and (max-width:650px){
.imgContainer {
width: 100% !important;
}
}

放大div 时,背景图像会变宽,并且不会显示图像的太多内容。当宽度为 400px 且高度为 340px 时,图像的内容将完整显示。当div 的宽度为 100% 并且图像的内容显示的不如 400px 宽时显示的那么多时,就会出现问题。如何解决这个问题?
提前感谢!

使用background-size: cover,您告诉浏览器确保图像覆盖整个元素,同时保持图像的原始纵横比。因此,可以预期更改HTML元素的纵横比将切断一些图像以实现这一目标。

为了使图像具有响应性,您必须确保图像的纵横比保持不变。

执行此操作的一种方法是使用如下所示的内容:

@media screen and (max-width:650px) {
.imgContainer {
width: 100%;
padding-bottom: 85%;
height: auto;
}
}

这会将填充设置为元素宽度的 85%,即 100/(400/340) = 85。假设您的div中没有其他内容,这将为您的图像提供适当的纵横比。

这可能会有所帮助。 注意:仅当图像的纵横比为 400:340(例如 800 x 680、600 x 510 等)时,它才有效。 注意:最后一个媒体查询中的 418 像素是基于当前填充和边距的经验值。您可能需要不同的值。

这是代码笔在实际操作

.imgContainer {
width: 400px;
height: 340px;
z-index: 1;
border: 0;
background: url("https://dummyimage.com/800x680/ccc/333");
background-repeat: no-repeat;
background-position: 50%;
background-size: cover;
border-radius: 0.25rem;
}
@media screen and (max-width: 650px) {
.imgContainer {
width: 100% !important;
background-size: contain;
}
}
@media screen and (max-width: 418px) {
.imgContainer {
background-size: cover;
}
}
<div class="imgContainer"></div>

最新更新