How to keep an image centered and responsive?

This is a dirty way around:

JSFiddle

<div class="shadow"><img class="logo" src="http://placehold.it/1000x1000" /></div>
div.shadow {
    position:absolute;
    max-width:45%;
    max-height:45%;
    top:50%;
    left:50%;
    overflow:visible;
}
img.logo {
    position:relative;
    max-width:100%;
    max-height:100%;
    margin-top:-50%;
    margin-left:-50%;
}

The trick is to use div.shadow as a "dimension holder", so percentage can work.

I call it dirty because the shadow div still possess some space, which will prevent mouse from pointing things underneath it. You can use pointer event to get around that, but then IE will be left behind, and the image itself would not be pointerble either.


Below is my suggestion. It works for any <div> <img> and ...

<div class="parent"> 

    <img class="responsive center" src="http://placekitten.com/800/600">

</div>

and the css code is:

.responsive{
   max-width:100%;
   max-height:100%;
 }

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

.parent{
  position: relative;
}

just find and test a live demo here: https://jsfiddle.net/veuodbk7/2/


Try with below css for the container for the image.

CSS:

width: 100%; text-align: center; margin-top:50%