Search code examples
cssinheritancehyperlinkcascading

CSS Cascading takes over inheritance, how to solve this?


We have run into a wall trying to figure out why CSS inheritance does not work as expected.

To describe the problem... I have a reusable CSS that defines various background colors and we switch backgrounds and foregrounds of various sections of the page per user configuration. The problem is that if one of my colors that gets assigned to a parent DIV and is defined further down in the CSS, than it overrides the CSS attributes defined at the child DIV. Case in point is this JSBin example - JSBin link!, where because bgBlack is defined in the CSS file AFTER bgWhite, the user agent is using properties of bgBlack even for contents of the bgWhite DIV! We need to make this work otherwise we will be in deep trouble with regards to user being able to switch colors etc. without involving developers. Any help and guidance is greatly appreciated!

<!DOCTYPE html>
<html>
<head>
   <meta name="description" content="[add your bin description]" />
   <meta charset=utf-8 />
   <title>JS Bin</title>
</head>
<body class="bgDark">

  <div class="bgWhite" style="margin:100px;padding:20px;height:200px;width:200px;">
  <h1>Hello World!</h1>
  <ul>
  <li><a href="#">This is a link 1</a></li>
  <li><a href="#">This is a link 2</a></li>
  <li><a href="#">This is a link 3</a></li>
  </ul>
  </div>

</body>
</html>

AND CSS for this is....

.bgWhite { background-color:white;color:black; }
.bgWhite a { color:black; }
.bgWhite a:hover { color:red; }

.bgDark { background-color:black;color:white; }
.bgDark a { color:white; }
.bgDark a:hover { color:blue; }

Solution

  • After hours and hours of messing around, and based on pointers provided by @GionaF, I embarked on a quest to find a meaningful solution that didn't require bloated CSS files or use of JavaScripts to manipulate things.

    I think I have nailed it! Posting the solution here to make sure this knowledge is available to the community if anyone else is trying to create a completely dynamic experience like we are, and is looking for a solution.

    Check out this JSFiddle DEMO to see how I solved this problem. All in all, I attribute about 40 hours committed to researching/investigating before posting question here, and then additional 5 or so hours after posting question here. That's good 45 hours one could save and still attain an elegant solution! Hope this helps someone. Good luck!