Search code examples
csscentering

Centering a relative sized image


I have a square image that I want to have centered on the screen. Problem is that I want the image to stay a square, while being not more than 80% of both the width and the height. I have used the following code, which makes my image 80% of the height (when height < width), and centers the image vertically, but not horizontally of course. When using a fixed width, I could have used margin-left: 50%; margin-right: 50%, but with relative size, this would set the left side of the image at 50%. Any ideas?

.my_img{
  max-width: 80%;
  max-height: 80%;
  margin-left: 10%;
  margin-top: 10%;
}


Solution

  • Try this:

    .my_img_container {
        position: relative;
    }
    .my_img {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%)
    }
    

    Here is a fiddle: http://jsfiddle.net/l0wskilled/voubtxrt/