Styling Pseudo Elements from Javascript Queries

CSS Variables to the Rescue

Chad Spencer
2 min readOct 2, 2020

Every now and again we need to target elements within a javascript component and manipulate their style. A common use case is the need to apply style to elements based on scroll position or resize events. It’s easy enough to query elements to add classes or apply style properties but, unfortunately, we can only apply those styles to the returned element directly and do not have access to pseudo element properties associated with the element.

The :before and :after pseudo elements are commonly used to reduce additional markup for stylistic elements that don’t have semantic value. In this example, we’re going to use :before and :after elements to conditionally render shadows at the top and bottom of a vertically scrollable table.

Here, we’re writing our styles as JavaScript objects, but the approach would look the same in plain old CSS, SASS, LeSS, you name it. You’ll notice on line 13, we’re setting the top property value to a CSS variable. We can now define this variable within JavaScript on the wrapper element and it will be inherited by the :before element.

With this simple example we’re going to detect the height of our table header and dynamically update that variable as the browser is resized and the text in the header may wrap to two lines. Pretty easy, huh?

Browser Support

For those of us who still have to worry about Internet Explorer 11, we won’t be able to use CSS variables. It’s good practice to set a fallback for that reason. In our case, we’re setting a default value of the top property on line 12 of the first example. IE will interpret this value first and not be able to compute the next line. This allows us to control the degradation of the experience and not be dependent upon that CSS variable being set.

More on CSS Variables

This was one of our team’s first usages of CSS variables in our component library. For anyone new to them, they’re worth checking out and incorporating into your codebase. Here are a couple of other great resources that explain them more in depth:

--

--