Image position equivalent to background position

前提是你 提交于 2019-12-08 07:11:12

问题


I am working on a website and I want to style an image like you style a background with background-position: center. Is there an equivalent to this for a regular image?

Thanks in advance,

Luuk

EDIT:

The image is responsive and contained in a container.

CSS:

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

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

回答1:


I would do something like this to position the image centered.

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

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



回答2:


You could go for display flex, but the support for IE is quite disastrous. If you care about browser support (which you should) go for the below example instead.

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

Make sure to add the prefixes for the transform attribute as well.

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




回答3:


Your desired result isn't exactly clear, but here are some options for two different interpretations:

Changing the display property of the image and setting the text alignment to its container will maintain it's native height and width while centering it in the container:

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

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

Demo: https://jsfiddle.net/5suo8tbw/

If you're trying to achieve a background fill with an img element you should consider using the object-fit: cover attribute. This will always fill your container's dimensions, maintain the image's aspect ratio, and center it in the container.

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

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

Demo: https://jsfiddle.net/5suo8tbw/1/

Here's a link to the spec: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

For cross browser support, check out the polyfill: https://github.com/anselmh/object-fit



来源:https://stackoverflow.com/questions/42236938/image-position-equivalent-to-background-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!