12 Weeks

Day 15. Learning CSS Inheritance, Specificity and Cascade

October 17, 2019

  • Every time I have a problem with my CSS, it’s always because I get one of these wrong.
  • Almost all property definitions are inheritable in CSS. If you set a background-color on the body, all elements will inherit it except that element has been styled otherwise.
  • Not all CSS properties are inherited. Imagine setting a border on the body, and every child element inherits the border color.
  • There’s a reference of all inheritable CSS properties, but most times common sense will tell you which ones should be.
  • Most times, an understanding of CSS inheritance will be enough. Other times, you’ll need to changes how elements inherit. We can do this with 4 properties; inherit, initial, unset and the new revert.
  • When we set a property to inherit, it takes the same value specified in the parent.
<ul>
  <li>list 1</li>
</ul>

ul{ border:1px solid red; } li { border: inherit; }

The li will have the border specified in the ul.

  • Setting a property to initial restores back user agent (browser) default styling.
  • unset takes a property back to its natural value (either inherit or initial) before any styling.
  • The last value is revert. It’s somehow difficult to explain. But think of it as a way to revert inheritance one level backwards. For example…
  • The background-color is set to inherit by default (background-color of parent will apply on children). If we change the value of background-color on another element

Quick and Scrappy notes from 12 weeks of learning UX Engineering for the web. More