Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Image magnifier using only one line of CSS

When you’re working with images on your website, it would be good if you can provide some sort of image magnification to your users when clicked/tapped/hovered over the images for better visibility.

The one way using which you can achieve this is using various lightbox libraries written in JavaScript. For instance, I use a library called Fluidbox (which is written in jQuery) to provide image magnification on my blog.

This is of course comes at a price since you’ll need to include the library on the page where you need this. And it adds to your website’s overall response time.

So, if you want to avoid these libraries (and JavaScript), you can use this quick and dirty way where the image magnification can be replicated using only “one line” of CSS.

One line of CSS all it takes

You heard it right. It all takes one line of CSS to achieve something like this. All you need to do is set the good old transform CSS property on image hover.

Here’s how this can look like.

img:hover {
    transform: scale(2.0);
}

And that is it! This is all you need and the image magnification will be there at your disposal.

Now, if you use it barebones like this, the transition to the magnified image would look jankier. This can be solved by using the transition CSS property and adding some smoothness to the animation. Couple this with the image’s cursor to pointer to make it seamless like so.

img {
    transition: transform .2s ease-out;
    cursor: pointer;
}

img:hover {
    transform: scale(2.0);
}

In Action

You can see this in action in this CodePen (Try opening it in another tab).

See the Pen Image Layout Shift Fixed Demo by Amit Merchant (@amit_merchant) on CodePen.

Gotchas

While this seems to work, this isn’t a perfect solution. For instance, you need to see which transform value would work for your interface using trial and error because if that isn’t nailed, the magnified image can even get out of the viewport.

So, you need to take care of things like these.

At the end of the day, it’s just a quick and dirty way as I said earlier but if you want something concrete, go with a JavaScript library.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?