图像位置相当于背景位置

时间:2017-02-14 21:53:08

标签: html css image position

我正在一个网站上工作,我想要设置一个图像样式,就像你用background-position:center设置背景样式。对于常规图像,是否有相同的效果?

提前致谢,

Luuk

修改

图像响应并包含在容器中。

CSS:

grouped

3 个答案:

答案 0 :(得分:3)

我会做这样的事情来将图像置于中心位置。

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

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

答案 1 :(得分:0)

你可以去展示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>

萨斯:

.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%);
  }
}

确保也为transform属性添加前缀。

小提琴:https://jsfiddle.net/k433b6up/

答案 2 :(得分:0)

您想要的结果并不完全清楚,但这里有两种不同解释的选项:

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

.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/

以下是规范的链接:https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

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

相关问题