如何在使用 object-fit: cover
时垂直居中图像?我希望图像始终为其容器宽度的 100%,并且当容器的高度小于图像的高度时,图像的顶部和底部将被裁剪。 object-fit: cover
默认只裁剪图像的底部。在下面的示例中,我希望图像的中心始终位于文本的正后方。
header {
max-height: 20em;
position: relative;
}
h1 {
position: absolute;
text-align: center;
top: 0;
transform: translateY(-50%);
width: 100%;
}
img {
object-fit: cover;
opacity: 0.2;
z-index: -1;
}
<header>
<h1>Page Title</h1>
<img src=https://upload.wikimedia.org/wikipedia/commons/9/92/Widdringtonia_whytei_Mulanje_Malawi.jpg>
</header>