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

Time:09-04

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?

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • css
  • Related