On this page
Computer and mobile phone

Determining viewport size – small, medium and large – using CSS

To get the viewport size using CSS in JavaScript, you can utilize the getComputedStyle method to access the content of a pseudo-element, such as ::before, which can be defined in your CSS media queries. This allows you to dynamically determine the viewport size category (e.g., small, medium, large) based on the current screen width, enhancing responsive design capabilities.

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.

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.

Note: the proper CSS selector syntax for ::before is ::before, not :before.

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.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Elevate your website’s accessibility with SiteLint

Your reliable source for inclusive online experiences. Our cutting-edge tools and services enable businesses to create user-friendly web environments. Join the digital inclusivity movement to discover new ways to engage and grow. Discover the SiteLint platform today and transform your online presence into a beacon of accessibility.

Real-user monitoring for Accessibility, Performance, Security, SEO & Errors (SiteLint)