Vertically align an image inside a div with responsive height

后端 未结 10 1974
遇见更好的自我
遇见更好的自我 2020-11-22 02:47

I have the following code which sets up a container which has a height that changes with the width when the browser is re-sized (to maintain a square aspect ratio).

10条回答
  •  时光说笑
    2020-11-22 03:45

    Use this css, as you already have the markup for it:

    .img-container {
        position: absolute;
        top: 50%;
        left: 50%;
    }
    
    .img-container > img {
      margin-top:-50%;
      margin-left:-50%;  
    }
    

    Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit

    This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:

    .img-container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%); /* add browser-prefixes */
    }
    

    Working JsBin solution: http://jsbin.com/ihilUnI/2/edit

提交回复
热议问题