Search code examples
cssstylesheet

Should I write the full hierarchy path in my CSS definitions for each element/class?


Should my stylesheet definitions mirror the DOM hierarchy? If I have:

<div id="container">
  <div class="item">
    <div class="property">
       <span id="1243"></span>
    </div>
  </div>
</div>

When I want to style each property, should I just say:

.property { color: red; }

Or should I do

#container .item .property { color: red;}

I've used both. I like the first for brevity and because I do not need to update it if the hierarchy changes, but the second helps me read the CSS.


Solution

  • As with any code (or any writing), you should write it to express your intended meaning as clearly and accurately as possible.

    So, if you want any element with a class of property that’s a descendant of an element with class of item which itself is a descendant of an element with an id of container to have these styles, then write #container .item .property.

    If you want an element with a class of property to have these styles regardless of what it’s a descendant of, then write .property. This is appropriate for classes that you want to use in a lot of different places on the site; e.g. button styles.

    One thing I would note is that every CSS selector you add increases the specificity of the selector, i.e. #container .item .property is more specific than .property. So styles applied with #container .item .property will require a selector of greater specificity to override them if you want to later, forcing you to write this longer selector out again. But I think that’s a secondary concern compared to writing what you mean.