DEV Community

dgloriaweb
dgloriaweb

Posted on

Center an image with css on responsive without distorting

Hi,
If my designer wants to see the middle of the image on the middle of any device screen, I take the height of the image, and calculate the left margin from it. I use an image that's near to rectangle, to be able to handle the wildest aspect ratio, in this case my app is portrait only. In this example my image is h=1000px w=776px. (Heads up, if your image might not be wide enough for some devices, also be prepared for landscape view. Better to use square image and decide if you use height or width as baseline.)

I position the image to the corner like this:

position: fixed;
top: 0;
left: 0;
Enter fullscreen mode Exit fullscreen mode

Then I set the height to 100vh

height: 100vh;
Enter fullscreen mode Exit fullscreen mode

Now I can calculate my offset for the image from the left, by adjusting the left-margin

margin-left: calc((-77.6vh / 2) + 50vw);
Enter fullscreen mode Exit fullscreen mode

briefly my image is 77.6vh wide (that's calculated from 100vh *77.6, because this is the aspect ratio), so I get half of that value, and move the whole thing 50vw to the right. That is where my image will start. I don't need to mess about with pixels, it's calculated for me.

Top comments (0)