Nested CSS Classes – Child class to override parent class?

Austin picture Austin · Jan 18, 2017 · Viewed 9.8k times · Source

The goal is to have an element's parent dictate it’s style. So .dark .light p would have light text, .dark p would have dark text, and .light .dark .light p would have light text.

The p element might not even be a direct child of .dark or .light so .light .dark div.wrap div.inner p would have dark text.

Because of the cascading nature of CSS, it seems to prefer the last rule. Is this even possible?

http://codepen.io/acondiff/pen/KaaqxP

Answer

Jon picture Jon · Jan 18, 2017

CSS follows the flow of the css document, therefore if .dark comes after .light in the CSS file, any element in your html with both classes will always display the .dark style.

.light {
  background: #ccc;
  }
.dark {
  background: #999;
  }
<p class="dark light">This will be dark  as it comes after light in the css file.</p>

!important

You can override the .dark styles by putting !important on your .light styles.

.light {
  background: #eee !important;
  }
.dark {
  background: #999;
  }
<p class="light dark">This will be light as the light styles has !important</p>

Alternatively you can apply the light styles to all elements and just override the elements you need to:

p {
  background: #eee;
}
.dark {
  background: #999;
}
<p>this will be light</p>

<p class="dark">this will be dark</p>