Vertically and Horizontally Center Image inside a Div, if you don't know Image's Size?

前端 未结 12 1096
庸人自扰
庸人自扰 2020-12-29 10:28

If I have a fixed sized container div, and an unknown sized image, how do I horizontally and vertically center it?

  • using pure css
  • using JQuery if css
12条回答
  •  轮回少年
    2020-12-29 11:00

    Check out my solution: http://codepen.io/petethepig/pen/dvFsA

    It's written in pure CSS, without any JS code. It can handle images of any size and any orientation.

    add another div to your HTML code:

    CSS code:

    .imageContainer {
      font-size: 0;
      text-align: center;
      width: 200px;  /* Container's dimensions */
      height: 150px;
    }
    img {
      display: inline-block;
      vertical-align: middle;
      max-height: 100%;
      max-width: 100%;
    }
    .imageContainer:before {
      content: '';
      display: inline-block;
      vertical-align: middle;
      height: 150px;
    }
    

    Update: I got rid of this

    element in favor of :before CSS selector

提交回复
热议问题