我在一页上使用与背景图像相同的图像,在另一页上使用图像元素。它们在两个页面上占据相同的空间,宽度和高度相同,但图像的位置不同。这是背景图片html:
<div class="frontpage-bg-image-wrapper">
<div class="header-bg-image frontpage-header-hero"></div>
<div class="bg-overlay overlay"></div>
</div>
这就是它的css:
.frontpage-header-image-div {
height: 100%;
.frontpage-bg-image-wrapper {
position: relative;
width: 100%;
min-height: 635px;
background-size: cover;
background: url('/wp-content/themes/sfk/assets/images/sfk-bg.png') no-repeat;
}
}
在另一页上,我有一个图像元素:
<div class="hero-image-wrapper">
<img src="<?php echo get_template_directory_uri(); ?>/assets/images/sfk-bg.png">
<div class="overlay"></div>
</div>
它的css:
.hero-image-wrapper img{
width: auto;
height: 100%;
}
但是图像的位置存在差异,我尝试使用object-fit: cover
,但它没有帮助。这是背景:
这是图像元素:
我该如何解决?
答案 0 :(得分:0)
我认为你的照片比容器小(特别是'高度'); background-size:cover会剪切外部图片以适合容器,但'img'标签不会。
答案 1 :(得分:0)
据我所知cover
加上min-height
正在裁剪您的图像,可能是因为它超出了图像的原始分辨率。
我会按照自己的方式创建自适应视频,将padding-bottom
添加为等于视频宽高比的百分比。如果您的图像是400x300,那么您将添加75%的填充
300 / 400 = 0.75 * 100 = 75%
这样做可以让元素以与图像相同的比例填充其容器的宽度。
img {
display: block;
max-width: 100%;
height: auto;
}
.container {
margin: 3rem auto;
width: 70%;
}
.bg {
position: relative;
background-image: url( 'http://lorempixel.com/800/400/city/4/' );
background-size: cover;
padding-bottom: 50%;
}
@media ( min-width: 1120px ) {
.bg {
max-width: 800px;
padding-bottom: 400px;
}
}
<div class="container">
<img src="http://lorempixel.com/800/400/city/4/">
<div class="bg"></div>
</div>
对于img
元素,我们已将其作为响应。大多数CSS框架使用img
上使用的三个属性作为响应式图像类。请注意,图像不会超出其原始分辨率。
要div
复制img
的响应式样式,我们需要使用媒体查询来防止图像扩展超出其原始分辨率以及更新底部填充。如果我们在限制图像宽度时不更改填充底部,那么最终会得到一个div
,占用的空间比背景图像多得多(在它下方创建大量空白区域)。 / p>
答案 2 :(得分:-1)
Yo可以尝试将背景大小设置为&#39;包含&#39;