
Determining viewport size – small, medium and large – using CSS
The browser viewport is the screen that actually shows the webpage. Determining its size might be handy when we want to provide some specific features for the viewport size. Here we want to utilize CSS media query and a little JavaScript to get the viewport size.
Note that quite often there is a way of designing the user interface and thinking about a specific device, like a mobile, tablet, or regular computer. This is a bit trap because designing the user interface should be in relation to the viewport size, not the device.
Let’s then take a look at the code.
CSS code for determining viewport size
@media only screen and (max-width: 36em) { :root body::before { content: "small"; display: none; } } @media only screen and (min-width: 36.0625em) and (max-width: 48em) { :root body::before { content: "medium"; display: none; } } @media only screen and (min-width: 48.0625em) { :root body::before { content: "large"; display: none; } }
The first block represents a small
viewport. The second block represents the medium
viewport. The third block represents a large
viewport.
How to get the value of the viewport size
JavaScript to the rescue. Let’s get the value that represents the viewport size.
function getViewportSize() { const styleContent = window .getComputedStyle(document.body, "content") .getPropertyValue("::before"); if (styleContent === null) { return "unknown"; } return styleContent.replace(/["']/g, ""); }
Practical example of viewport size determination
See the workable example that determines the viewport size using CSS with a little JavaScript that helps to get the value.
Comments