至少有两种方法可以接近它。
1) 将您的图像绝对定位在容器内。
<div class="entry-content">
<div class="img-wrapper">
<img id="fit" src="..." alt/>
</div>
</div>
如果我们假设您希望图像占浏览器宽度和高度的 100%,那么您的 css 应该如下所示(注意我忽略了 entry-content,因为我不太确定其余内容是否会在新的 div 中 - 在您的示例中似乎很不清楚)。
.img-wrapper {
position:relative;
width:100vw;
height:100vh;
overflow:hidden;
}
.img-wrapper img {
position:absolute;
top:50%
left:50%;
transform:translate(-50%,-50%);
}
这种方法的噱头 - 它只适用于由图像纵横比决定的某些场景。一种解决方法是使用 JavaScript sn-p,您可以在文档加载和调整大小时绑定它。然后,您可以使用以下 JavaScript 来计算特定场景下图像的最佳尺寸:
function checkImg() {
var img = document.getElementById('fit'));
var section = document.getElementsByClassName('entry-content')[0];
var imgheight = img.offsetHeight;
var sectionheight = section.offsetHeight;
var imgwidth = img.offsetWidth;
var sectionwidth = section.offsetWidth;
var imgRatio = imgheight / imgwidth;
var scrRatio = sectionheight / sectionwidth;
if (scrRatio > imgRatio) {
var finalHeight = sectionheight;
var scale = finalHeight / imgheight;
var finalWidth = imgwidth * scale;
} else {
var finalWidth = sectionwidth;
var scale = finalWidth / imgwidth;
var finalHeight = imgheight * scale;
}
img.style.height = finalHeight + 'px';
img.style.width = finalWidth + 'px';
}
}
请记住,在加载文档后运行此函数至关重要,而不仅仅是准备好,否则如果在加载之前执行该函数,它将无法获得正确大小的图像。
同时如果你在resize时不触发,图片的宽高不会改变。
2) 使用 css 背景属性。正如 ArtisticPhoenix 指出的那样,您不能在图像标签上使用背景属性。但是,您可以将图像设置为元素的背景。然后您可以使用以下内容:
<div class="entry-content">
<div class="img-wrapper">
</div>
</div>
请注意,您不会将图像与 img 标签一起放在这里,而是必须在 CSS 中指定 background-image 属性的来源,如下所示:
.img-wrapper {
position:relative;
width:100vw;
height:100vh;
overflow:hidden;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
background-image:url('http://zm.jcreator.eu/wp-content/uploads/2019/03/home_1.jpg');
}
由于您使用的是 WordPress,因此您可能希望使用您在 CMS 中选择的图像。在这种情况下,您只需要使用内联样式指定背景图像:
<div class="entry-content">
<div class="img-wrapper" style="background-image:url('<?php echo your_php_function_to_get_img_url(); ?>')">
</div>
</div>