Center Oversized Image in Div

前端 未结 12 1632
予麋鹿
予麋鹿 2020-11-27 08:52

I have been trying to sort out how to center an oversized image within a div using css only.

We are using a fluid layout, so the width of the image containers varies

12条回答
  •  迷失自我
    2020-11-27 09:49

    Put a large div inside the div, center that, and the center the image inside that div.

    This centers it horizontally:

    HTML:

    CSS:

    .imageContainer {
      width: 100px;
      height: 100px;
      overflow: hidden;
      position: relative;
    }
    .imageCenterer {
      width: 1000px;
      position: absolute;
      left: 50%;
      top: 0;
      margin-left: -500px;
    }
    .imageCenterer img {
      display: block;
      margin: 0 auto;
    }
    

    Demo: http://jsfiddle.net/Guffa/L9BnL/

    To center it vertically also, you can use the same for the inner div, but you would need the height of the image to place it absolutely inside it.

提交回复
热议问题