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

前端 未结 12 1129
庸人自扰
庸人自扰 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 10:55

    Using display: table-cell trick for div

    Working correctly in: Firefox, Safari, Opera, Chrome, IE8

    CSS example:

    div {
      width: 300px;
      height: 300px;
      border: 1px solid black;
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
    img {
      display: inline;
    }
    

    HTML example:

    Firefox example

提交回复
热议问题