In this example a select
field is used to change the zoom level of the element.
HTML
In this first block, of HTML, a select
field is defined with the different zoom
values to be used.
<section class="controls">
<label for="zoom"
>Zoom level
<select name="zoom" id="zoom">
<option value="0.5">Extra Small</option>
<option value="0.75">Small</option>
<option value="normal" selected>Normal</option>
<option value="1.5">Large</option>
<option value="2">Extra Large</option>
</select>
</label>
</section>
In this second block a not supported message is added that will be hidden if the browser supports zoom
.
<p class="zoom-notice">CSS zoom is not supported</p>
The final block just defines the content that will be zoomed.
<section class="content">
<h1>This is the heading</h1>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Placeat inventore
ea eveniet, fugiat in consequatur molestiae nostrum repellendus nam
provident repellat officiis facilis alias facere obcaecati quos sunt
voluptas! Iste.
</p>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Placeat inventore
ea eveniet, fugiat in consequatur molestiae nostrum repellendus nam
provident repellat officiis facilis alias facere obcaecati quos sunt
voluptas! Iste.
</p>
</section>
CSS
In this first block, of CSS, we are setting the starting value for the --zoom-level
using custom properties and then using that as the value for zoom
on the content block.
html {
--zoom-level: normal;
}
.content {
max-width: 60ch;
margin: auto;
zoom: var(--zoom-level);
}
In this final CSS block we are checking to see if the browser supports zoom
and if so setting the not supported message to display: none;
.
@supports (zoom: 1) {
.zoom-notice {
display: none;
}
}
JavaScript
This JavaScript watches for a change in the select field and sets the new value for --zoom-level
on the content section
, e.g. style="--zoom-level: 1.5;"
.
const zoomControl = document.querySelector("#zoom");
const content = document.querySelector(".content");
const updateZoom = () => {
content.style = `--zoom-level: ${zoomControl.value}`;
};
zoomControl.addEventListener("change", updateZoom);
Result