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

前端 未结 12 1094
庸人自扰
庸人自扰 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:53

    With CSS3 flexbox, you will not need any more hacks to center the image. It is currently supported by all modern browsers. Check out Can I use flexbox?

    .container {
      display: flex; /* Flexible layout container */
      justify-content: center; /* Horizontal center alignment */
      align-items: center; /* Vertical center alignment */
      background: lightblue;
      /* Fixed size container */
      height: 300px;
      width: 300px;
    }

提交回复
热议问题