我有一个用户图像,我想用窗口向上和向下缩放,以便高度始终为100%并且图像保持居中。
此示例在窗口调整大小时进行缩放,但高度不会保持在100%,因此会在底部被切断。
.user {
width: 100%;
height: 100%;
object-fit: cover;
object-position: 50% 0%;
}
此示例效果很好,除了浏览器窗口的宽度小于图像的宽度时,右侧也会被切断。
我做想要裁剪图像,但我希望右侧和左侧裁剪同样。
.user {
object-position: center;
display: block;
height: 100%;
margin-left: auto;
margin-right: auto;
}
以下是我希望在浏览器水平/垂直缩放时如何显示图像的示例。
答案 0 :(得分:1)
一个想法是使用这样的多个背景:
我使用了多个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>
&#13;
<强>更新强>
为了避免在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%;
}
&#13;
<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>
&#13;
答案 1 :(得分:0)
我喜欢你的问题!我从一个不同的角度接近它,并试图使用背景而不是img元素。请在此处查看结果:
https://codepen.io/Varin/pen/xYqXQe
body, html {
height: 100vh;
margin: 0;
}
.bg-shine {
height: 100vh;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-image: url("http://t.motionelements.com/stock-video/design-elements/me1656952-blue-sunrise-background-hd-a0120-poster.jpg");
position: relative;
}
.image {
padding:0;
margin:0;
width: 100%;
height:100%;
position:absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);
background-image:url('http://icons.iconarchive.com/icons/paomedia/small-n-flat/512/user-male-icon.png');
background-repeat: no-repeat;
background-position: center center;
background-size: auto 100%;
}
<div class="bg-shine">
<div class="image">
</div>
</div>