center image in div with overflow hidden

后端 未结 12 1675
攒了一身酷
攒了一身酷 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 19:53

    Found this nice solution by MELISSA PENTA (https://www.localwisdom.com/)

    HTML

    CSS

    div.wrapper {
      height:200px;
      line-height:200px;
      overflow:hidden;
      text-align:center;
      width:200px;
    }
    div.wrapper img {
      margin:-100%;
    }
    

    Center any size image in div
    Used with rounded wrapper and different sized images.

    CSS

    .item-image {
        border: 5px solid #ccc;
        border-radius: 100%;
        margin: 0 auto;
        height: 200px;
        width: 200px;
        overflow: hidden;
        text-align: center;
    }
    .item-image img {
        height: 200px;    
        margin: -100%;
        max-width: none;
        width: auto;    
    }
    

    Working example here codepen

提交回复
热议问题