gengns ES

An entry from the gengns log, written by Génesis García Morilla · · CSS3, HTML5, JavaScript

CSS zoom

Easy zoom in, zoom out, normal zoom and zoom adjusted to the container with CSS and JS.

If you want to change the zoom, just add or subtract from the original zoom CSS property.

document.querySelector("#zoomin").addEventListener("click", function() {
    $area.style.zoom = Number($area.style.zoom) + 0.2;
});

You can also set up maximum and minimum values to avoid infinite zoom.

To adjust an area or image to your container you need to divide the width or height depending of what you want to adjust.

document.querySelector("#zoomfix").addEventListener("click", function() {
    $area.style.zoom = $container.offsetWidth / $area.offsetWidth;
});

Here a real example:

JavaScript

var min = 0.2;
var max = 3;

var $container = document.querySelector("div");
var $area = document.querySelector("img");
$area.style.zoom = 1.0;

document.querySelector("#zoomreset").addEventListener("click", function() {
	$area.style.zoom = 1.0;
});
document.querySelector("#zoomin").addEventListener("click", function() {
    if (Number($area.style.zoom) >= max) return;
	$area.style.zoom = Number($area.style.zoom) + 0.2;
});
document.querySelector("#zoomout").addEventListener("click", function() {
    if (Number($area.style.zoom) <= min) return;
	$area.style.zoom = Number($area.style.zoom) - 0.2;
});
document.querySelector("#zoomfix").addEventListener("click", function() {
	$area.style.zoom = $container.offsetWidth / $area.offsetWidth;
});

HTML

<div>
    <img src="https://upload.wikimedia.org/wikipedia/commons/8/80/Atom_editor_logo.svg">
</div>
<button id="zoomreset">0</button>
<button id="zoomin">+</button>
<button id="zoomout">-</button>
<button id="zoomfix">▣</button>

CSS

div {
    width: 250px;
    height: 250px;
    background-color: #333;
    overflow: auto;
}
button {
    margin-top: 5px;
    padding: 5px 10px;
    cursor: pointer;
    color: #bfbfbf;
    background-color: #333;
}
img {
    padding: 5px;
}
Open in JSFiddle

Tags: zoom