我创建了一个名为“responsive_image”的类的 div,在该 div 中我有一个 img 标签。代码是,
<div class="responsive_image">
<img src="img1.png"/>
</div>
CSS代码是,
.responsive_image {
position: relative;
background: url(images/laptop.png) no-repeat center #f0f0f0;
width: 100%;
height: 190px;
text-align: center;
background-size: contain;
background-position: center;
}
.responsive_image img {
width: 240px;
height: 160px;
position: absolute;
top: 6%;
left: 16%;
max-width: 100%;
height: auto;
display: block;
}
实际上,laptop.png
图像是笔记本电脑的原始图像,尺寸为 310x186,其中一张尺寸为 240x160 的图像应该正确固定在笔记本电脑图像中。
从上面的代码来看,一切似乎都很完美,但是在进行响应时,每次我都需要调整 .responsive_image img
中的顶部和左侧部分。有什么解决方案可以让我不需要改变顶部和左侧吗?
最佳答案
您必须从 .responsive_image
类中删除 width:100%
。并根据您的笔记本电脑图像大小提供 width:310px
您还使用了 percentage
和 top and left
位置。用 pixel
改变它。根据屏幕大小,百分比始终具有动态行为。仅在构建 html 的主要结构时使用百分比。
.responsive_image {
position: relative;
background: url(images/laptop.png) no-repeat center #f0f0f0;
width: 310px;
height: 190px;
text-align: center;
background-size: contain;
background-position: center;
}
.responsive_image img {
width: 240px;
height: 160px;
position: absolute;
top: 20px;
left: 20px;
max-width: 100%;
height: auto;
display: block;
}
关于html - css中背景图片的响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901928/