James McGrath

Changing pseudo elements with CSS Custom Properties

Feb 02, 2020
1 minute

As far as I know, there wasn’t any way to dynamically change the CSS properties of pseudo-elements. Now that CSS custom properties are supported in the latest browsers, there are two ways in which this can be done. The following codepen demonstrates it.

The first way is so to set the pseudo-elements value globally and then modify the global custom property in the :root.

:root {
    --global-css-var: yellow;
}

a:hover {
color: var(--global-css-var);
}

This is how to modify the :root the style needs to change on the documentElement.


document.documentElement.style.setProperty('--global-css-var', 'green' );

The other way to change the pseudo-element property is to set the custom property locally.


a {
	--local-css-var: purple;

	color: black;
}

a:hover {
	color: var(--local-css-var);
}


To change the :hover color, change the custom property of the <a>;


const links = document.querySelectorAll('a');
links.forEach(link => {
	link.style.setProperty('--local-css-var', 'magenta');
});

Between the two methods, the first way of changing the custom property globally is better because it doesn’t loop through a list of elements.