Over a million developers have joined DZone.

Issue With CSS Variables and Button Background Styling

DZone's Guide to

Issue With CSS Variables and Button Background Styling

Ever run into an issue with a after you set the background color? Read on for a solution to such a situation that this author uncovered.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

I’ve been creating a <share-button> custom element and after I launched it, I noticed that something was funky with the default button styling. They were white instead of gray.

I needed to be able to dynamically let the developer style the button that was in my Shadow DOM, and to do that you have to use CSS Variables. In Chrome (at least… I need to test other browsers) there seems to be no way to have a button with a background-color whose value is defined by a CSS Variable, even if the value of the CSS variable is ‘initial’, ‘inherit’, or something undefined, and have it appear as the default button.

The instant you do anything with the background color it changes the <button> to be non-natively styled.

For example:

    #button2 {
        --but2: initial;
        background-color: var(--but2);
<button>Button 1</button>
<button id="button2">Button 2</button>


Here is an  image of it not working for me:

There is a way around this. My colleague Surma suggested that I should try and get the default computed styles, add that to the custom CSS variable, and then apply that to the background-color.

It works, but it is hacky.

    #button3 {
        --but3: initial;
<button>Button 1</button>
<button id="button3">Button 3</button>
    const defaultButtonStyle = window.getComputedStyle(button3);
    button3.style.setProperty('--but3', defaultButtonStyle.backgroundColor);
    button3.style.backgroundColor = 'var(--but3)';

Here is an image of it working for me:

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

css ,dom ,css variables ,web dev

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}