Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 19, 2021 04:25 pm GMT

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;

Then I set the height to 100vh

height: 100vh;

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

margin-left: calc((-77.6vh / 2) + 50vw);

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.


Original Link: https://dev.to/dgloriaweb/center-an-image-with-css-on-responsive-without-distorting-4mj4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To