Zoom whole site on resizing browser window
On the desktop version of the Shmøergh website I wanted to keep the proportions of the content regardless of the browser window size, something like this:
The first implementation I came up with was to choose a base width as an arbitrary value for the 100% view (e.g. 1580px), and calculate a scale factor which then I applied to a top level wrapper container:
<div class="wrapper">
All the content here
</div>
<script>
function resizeContent() {
// Get the current width of the window
const windowWidth = window.innerWidth;
// Set the base width for the design (100% at this width)
const baseWidth = 1580;
// Calculate the scale factor based on the viewport width
const scaleFactor = windowWidth / baseWidth;
// Apply the scale factor to the container
const wrapper = document.querySelector('.wrapper');
wrapper.style.transform = `scale(${scaleFactor})`; // Scale the container
}
// Run the function once when the page loads
resizeContent();
// Adjust the scale when the window is resized
window.addEventListener('resize', resizeContent);
</script>
This worked pretty well until I added Ghost comments to my page which has a couple elements with position: fixed
which doesn't work within a container that has its transform
attribute set.
So I came up with a much more elegant solution that doesn't involve Javascript at all.
The Shmøergh site uses TailwindCSS which sets sizes in rem
:
This allows to set the font size of the html
tag to any value, including dynamic sizes too (!) and it'll cascade size changes all the way in the whole site. So all I had to do was to set html
to be proportional to the width of browser window:
html {
font-size: 1vw;
}
💥 And voilà, the whole site "zooms" as you resize the window.