agsamek agsamek - 4 months ago 10
CSS Question

How to add zoom in / out on click to all img html tags?

What is the simplest way to add zoom in / out on click to all images in an html document (img tags)?

I'm editing a document in HTML and would like to stay focused on the content of this document. Due to this I would rather avoid adding any additional div elements around img element, at least in the source document.

Is there any simple javascript module which I can just plug-in for this purpose?

To clarify. Simple:

img:hover {
height: 400px;
}


would almost do the job for me but:


  1. it cracks the layout

  2. works with hover and I would prefer work on click.



Based on Paulie_D answer here is what I eventually came up with:

Works fine in Chrome & IE9. I tried to add this script to Paulie_D answer but my edit was rejected there - so here it is:

<style>
img {
cursor: pointer;
transition: -webkit-transform 0.1s ease
}
img:focus {
-webkit-transform: scale(2);
-ms-transform: scale(2);
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function(){
var imgs = document.querySelectorAll('img');
Array.prototype.forEach.call(imgs, function(el, i) {
if (el.tabIndex <= 0) el.tabIndex = 10000;
});
});
</script>

Answer

Anything that changes the height of the image is likely to break your layout.

Accordingly you should be looking at (IMO) transform: scale(x)

JSFiddle Demo (using :active as mousedown - just click & hold)

CSS

img {
    transition: -webkit-transform 0.25s ease;
    transition: transform 0.25s ease;
}

img:active {
    -webkit-transform: scale(2);
    transform: scale(2);
}
Comments