Bamba
Bamba

Reputation: 33

How to get the background color of element within CSS file?

I have an animation in my application, and I also have a dark mode theme. The animation have the following transitions, inside @keyframes :
(It has more phases, but it's irrelevant for my question)

0% {
    transform: rotateX(0);
    background: #fff;
    border-color: black;
    }

45% {
    transform: rotateX(90deg);
    background: #fff;
    border-color: black;
    }

I want to change the background property, so it will check what is the background color right now, and then apply the same value. Something like

  background: var(--background-color);

(When I declare --background-color to be the current background color)
What is the right way to do it?

Upvotes: 1

Views: 1773

Answers (2)

Bamba
Bamba

Reputation: 33

I got a solution to my problem, but it's a bit different than my question. Instead of checking what is the background color right now, I declared a css variable in Body of the main page. This variable will contain the background color of the current theme.

Whenever the theme is changed, I also change the css variable with:

document.body.style.setProperty('--current-background', 'backgroundColor');

but instead of backgroundColor, I just write the background color of the theme that user has switched to.

In my animation, I set

background-color: var(--current-background);

and it works as I wanted it to.

Upvotes: 1

harp
harp

Reputation: 109

You can use JS to get the background of an element and set another element to that color. Checkout:

https://www.w3resource.com/jquery-exercises/jquery-css-exercise-1.php

Upvotes: 1

Related Questions