问题
我有一个用户图像,我想用窗口向上和向下缩放,以便高度始终为100%并且图像保持居中.
例1
此示例在调整窗口大小时进行缩放,但高度不会保持在100%,因此会在底部被切断.
.user {
width: 100%;
height: 100%;
object-fit: cover;
object-position: 50% 0%;
}
例2
此示例完美地工作,除了当浏览器窗口的宽度小于图像的宽度时,右侧被切断.
我确实希望裁剪图像,但我希望右侧和左侧均匀裁剪.
.user {
object-position: center;
display: block;
height: 100%;
margin-left: auto;
margin-right: auto;
}
视觉示例
下面是我希望在浏览器水平/垂直缩放时如何显示图像的示例.
最佳答案 一个想法是使用这样的多个背景:
我使用了多个div来说明不同的大小
body,
html {
height: 100vh;
margin: 0;
}
.bg-shine {
background-position: center;
background-repeat: no-repeat;
background-size: auto 100%, cover;
background-image: url("https://icons.iconarchive.com/icons/paomedia/small-n-flat/512/user-male-icon.png"), url("https://t.motionelements.com/stock-video/design-elements/me1656952-blue-sunrise-background-hd-a0120-poster.jpg");
}
<div style="display: inline-block;">
<div class="bg-shine" style="height:100px;width:400px;">
</div>
<div class="bg-shine" style="height:100px;width:200px;">
</div>
</div>
<div style="display: inline-block;">
<div class="bg-shine" style="height:200px;width:100px;">
</div>
</div>
更新
为了避免在CSS中使用图像,您可以考虑内联样式和用户图像的单独div,以便您使用与使用图像标记几乎相同的标记:
body,
html {
height: 100vh;
margin: 0;
}
.bg-shine {
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-image: url("https://t.motionelements.com/stock-video/design-elements/me1656952-blue-sunrise-background-hd-a0120-poster.jpg");
}
.bg-shine>div {
background-size: auto 100%;
background-position: center;
background-repeat: no-repeat;
height:100%;
}
<div style="display: inline-block;">
<div class="bg-shine" style="height:100px;width:400px;">
<div style="background-image:url('https://icons.iconarchive.com/icons/paomedia/small-n-flat/512/user-male-icon.png')"></div>
</div>
<div class="bg-shine" style="height:100px;width:200px;">
<div style="background-image:url('https://icons.iconarchive.com/icons/paomedia/small-n-flat/512/user-male-icon.png')"></div>
</div>
</div>
<div style="display: inline-block;">
<div class="bg-shine" style="height:200px;width:100px;">
<div style="background-image:url('https://icons.iconarchive.com/icons/paomedia/small-n-flat/512/user-male-icon.png')"></div>
</div>
</div>