保持图像居中,同时保持100%的高度,并且仅延伸/裁剪侧面

Pol*_*ami 5 html css css-position background-image

问题

我有一个用户图像,我想通过窗口缩放该图像,以使高度始终为100%,并且图像保持居中。


例子1

此示例随着调整窗口大小而缩放,但高度不会保持在100%,因此会在底部被截断。

.user {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: 50% 0%;
}
Run Code Online (Sandbox Code Playgroud)

CodePen示例1


例子2

这个示例非常完美,除了浏览器窗口的宽度小于图像的宽度之外,右侧的内容也被切除。

确实希望对图像进行裁剪,但是我希望对左右两侧进行均等的裁剪。

.user {
    object-position: center;
    display: block;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)

CodePen示例2


视觉范例

这是当浏览器水平/垂直缩放时如何显示图像的示例。

我的形象

Tem*_*fif 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");
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

更新

为了避免在 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%;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)