This example shows a container with text inside it, and a button that can be clicked to make the container width narrower or wider depending on reading preference.
HTML
The HTML contains a single <section>
element containing child text content, plus a <button>
to change the <section>
width.
<section class="easy-reader">
<h2>Easy reader</h2>
<p>
Eius velit aperiam ipsa. Deleniti eum excepturi ut magni maxime maxime
beatae. Dicta aperiam est laudantium ut illum facere qui officiis. Sunt
deleniti quam id. Quis sunt voluptatem praesentium minima dolorum autem
consequatur velit.
</p>
<p>
Vitae ab incidunt velit aspernatur deleniti distinctio rerum. Et natus sed
et quos mollitia quia quod. Quae officia ex ea. Ducimus ut voluptatem et et
debitis. Quidem provident laboriosam exercitationem similique deleniti.
Temporibus vel veniam mollitia magni unde a nostrum.
</p>
<button class="width-adjust">Narrower</button>
</section>
CSS
In the CSS, we set the <section>
's width
to a default of fit-content
. We then define two sets of @keyframes
, narrower
, which animates from fit-content
to 70% of fit-content
(calculated using calc-size()
), and wider
, which animates the same values but in the opposite direction. Finally, we attach those animations to two classes — .narrower
and .wider
. Each animation is defined to last one second and to keep the final state applied once finished.
section {
width: fit-content;
}
@keyframes narrower {
from {
width: fit-content;
}
to {
width: calc-size(fit-content, size * 0.7);
}
}
@keyframes wider {
from {
width: calc-size(fit-content, size * 0.7);
}
to {
width: fit-content;
}
}
.narrower {
animation: narrower 1s ease forwards;
}
.wider {
animation: wider 1s ease forwards;
}
The rest of the CSS has been hidden for brevity.
JavaScript
The JavaScript provides a narrower/wider toggle that applies the relevant class to the <section>
when the button is clicked:
const widthAdjustBtn = document.querySelector(".width-adjust");
const easyReader = document.querySelector(".easy-reader");
widthAdjustBtn.addEventListener("click", () => {
if (easyReader.classList.length === 1) {
easyReader.classList.add("narrower");
widthAdjustBtn.textContent = "Wider";
} else if (easyReader.classList.contains("wider")) {
easyReader.classList.replace("wider", "narrower");
widthAdjustBtn.textContent = "Wider";
} else if (easyReader.classList.contains("narrower")) {
easyReader.classList.replace("narrower", "wider");
widthAdjustBtn.textContent = "Narrower";
}
});
Result
Try clicking the <button>
a few times to adjust the <section>
between the wide and narrow reading width, achieved by manipulating the width
based on the fit-content
value.