center image in div with overflow hidden

后端 未结 12 1702
攒了一身酷
攒了一身酷 2020-12-08 18:59

I have an image of 400px and a div that is smaller (the width is not always 300px as in my example). I want to center the image in the div, and if there is an overflow, hide

12条回答
  •  没有蜡笔的小新
    2020-12-08 20:04

    For me flex-box worked perfect to center the image.

    this is my html-code:

    and this i used for css: I wanted the Image same wide as the wrapper-element, but if the height is greater than the height of the wrapper-element it should be "cropped"/not displayed.

    .img-wrapper{
      width: 100%;
      height: 50%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center; 
    }
    img {
      height: auto;
      width: 100%;
    }
    

提交回复
热议问题