DEV Community

dgloriaweb
dgloriaweb

Posted on

1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more