center image in div with overflow hidden

后端 未结 12 1705
攒了一身酷
攒了一身酷 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:38

    This issue is a huge pain in the a.. but I finally got it. I've seen a lot of complicated solutions. This is so simple now that I see it.

    .parent {
      width:70px;
      height:70px;
    }
    
    .child {
      height:100%;
      width:10000px; /* Or some other impossibly large number */
      margin-left: -4965px; /* -1*((child width-parent width)/2) */
    }
    
    .child img {
      display:block; /* won't work without this */
      height:100%;
      margin:0 auto;
    }
    

提交回复
热议问题