Skip to main content

Detecting Element Visibility Using CSS

Written by on .

#react, #html, #css, #performance


A big part of building Pillser is to learn how to build websites using modern web technologies. In this post, I will share an approach to detecting if element is visible on the screen using the content-visibility CSS property.

The problem with the broadly documented solutions is that they rely on IntersectionObserver which can be very resource intensive, especially when you need to monitor visibility of hundreds of elements on the page.

My use case required me to know when elements are visible (or about to be visible) on the screen for pages that list hundreds of supplements, e.g.,

If you are thinking that's a lot of products to list on a single page, you are right. I plan to refactor the UI, but I was curious to see how I could improve the performance of the current UI.

This is where the content-visibility CSS property comes in. It enables the browser to bypass layout and rendering work for elements not immediately needed by a user. This makes the initial render of the page faster (see LogRocket article about using content-visibility to boost rendering performance), but it also produces contentvisibilityautostatechange event when element's visibility changes.

To trigger the event, the element must have content-visibility: auto set on it. Then, you have to add a listener to the event and check if element was skipped (i.e., it was not visible).

const element = document.getElementById('my-element');

element.addEventListener('contentvisibilityautostatechange', (event) => {
  if (event.skipped) {
    // element is not visible
  } else {
    // element is visible
  }
});

This approach not only speeds up the initial rendering but also provides an efficient way to detect visibility changes without the heavy resource usage of IntersectionObserver.

Whether this approach is good for your use case depends on your specific requirements. In my case, I didn't need to know whether element is in viewport or not; I just needed to know whether the browser thinks it is about to be visible or not. If you need to know the actual visibility of the element, you can combine this approach with IntersectionObserver to get more accurate results.

Pillser helps you make informed health decisions by providing comprehensive, unbiased information about supplements. This includes detailed research on supplement ingredients, their benefits, potential risks, and their overall efficacy. You can contribute by sharing your feedback and suggestions.

Send us an email at support@pillser.com.