图像位置等于背景位置

Image position equivalent to background position

我正在一个网站上工作,我想像您使用 background-position: center 设置背景样式一样设置图像样式。是否有与此等效的常规图像?

提前致谢,

卢克

编辑:

图像是响应式的并且包含在容器中。

CSS:

.img-container {
max-height: 300px;
overflow: hidden;
}

.img-container img {
max-height: 100%;
max-width: 100%;
}

我会做这样的事情来将图像居中。

.img-container {
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 300px;
  overflow: hidden;
}

.img-container img {
  max-height: 100%;
  max-width: 100%;
}

您可以选择 display flex,但对 IE 的支持非常糟糕。如果您关心浏览器支持(您应该关心),请改用下面的示例。

<div class="list">
  <div class="item">
    <img src="https://unsplash.it/50/40" alt="">    
  </div>
  <div class="item">
    <img src="https://unsplash.it/50/60" alt="">
  </div>
  <div class="item">
    <img src="https://unsplash.it/50/30" alt="">
  </div>
  <div class="item">
    <img src="https://unsplash.it/50" alt="">
  </div>
</div>

Sass:

.list {
  text-align: center;
}

.item {
  position: relative;
  display: inline-block;
  vertical-align: top;
  height: 5rem;
  width: 5rem;
  background: red;

  img {
    position: relative;
    top: 50%; 
    transform: translateY(-50%);
  }
}

确保也为转换属性添加前缀。

Fiddle: https://jsfiddle.net/k433b6up/

您想要的结果并不十分清楚,但这里有一些用于两种不同解释的选项:

更改图像的显示 属性 并将文本对齐设置为与其容器对齐将在将其置于容器中心的同时保持其原始高度和宽度:

.img-container {
    max-height: 300px;
    overflow: hidden;
    text-align: center;
}

.img-container img {
    display: inline-block;
    max-height: 100%;
    max-width: 100%;
}

演示:https://jsfiddle.net/5suo8tbw/

如果您尝试使用 img 元素实现背景填充,您应该考虑使用 object-fit: cover 属性。这将始终填充容器的尺寸、保持图像的纵横比并将其居中放置在容器中。

.img-container {
    max-height: 300px;
    overflow: hidden;
}

.img-container img {
    object-fit: cover;
    height: 100%;
    width: 100%;
}

演示:https://jsfiddle.net/5suo8tbw/1/

这是规范的 link:https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

对于跨浏览器支持,查看 polyfill:https://github.com/anselmh/object-fit

img

object-fitobject-position 属性等同于具有 background-image 的块元素的 background-sizebackground-position 属性,分别。在以下代码段中,请注意容器大小为 300px * 300px 而图像大小为 500px * 300px.

.imageContainer {
   margin: 15px;
   width: 300px;
   height: 300px;
   border: 5px solid lightgreen;
 }

.image {
   width: 100%;
   height: 100%;
   object-fit: cover;
   object-position: center;
}
<div class='imageContainer'>
  <img class='image'src='https://picsum.photos/500/300' alt='lorem picsum' />
<div>