1

I have a .card class with a CSS variable that has a white background color: --card-bg: #fff; and .card { background-color: var(-card-bg); }. When you use the class in a div it will have the background color white but if you have a child with the same class .card the idea is to change the color to --card-bg: #f9f9f9;. Then if another div is put inside these two I want to change it back to white. The intention is for the .card class to change the background color between #fff and #f9f9f9 depending on the parent. Could someone help me with that please?

Ben.S
  • 708
  • 1
  • 5
  • 24
  • 1
    I think it will be better if you try to add some code or image of what you are trying to do – Ben.S Jun 21 '21 at 07:24

1 Answers1

1

Obviously, you cannot have 2 distinct values of the same variable at the same time. The solution would be to use two variables:

--card-bg: #fff;
--card-bg-alt: #f9f9f9;

.card { background-color: var(--card-bg); }
.card .card { background-color: var(--card-bg-alt); }
.card .card .card { background-color: var(--card-bg); }
/* ...and so on... */
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
  • I tried to do this, but when I have 4, 6 or more divs with parents that have the .card class it becomes cumbersome. You would have to set a lot of rules: `.card .card .card .card {...}` That's not very optimal. – Mauricio Mendoza Jun 20 '21 at 09:17
  • This is true, but is there a real-life requirement to have 6 (or more) levels of cards? – Zoli Szabó Jun 20 '21 at 09:20
  • Yes! I am in a great project. I mean it has a lot of complexity. However, even though I didn't want to, I will have to use JavaScript to solve the problem. – Mauricio Mendoza Jun 20 '21 at 09:23