Local CSS classes

It’s possible to encounter naming conflicts when using CSS classes. This is most probable for classes intended to be used exactly in a certain context:

  • as a modifier in conjunction with a base class;
  • as a subordinate part of a context selector or a child selector.

Coincidence of names of such local (subordinate) classes with names of global (independent) ones leads to cascading inheritance of styles of global classes by local classes that have same names as global ones. But, on presentation level, local classes are not necessarily related to global ones having same names, therefore such coincidence can be undesired.

.products {...} /* Catalog of products */
BODY.home .products {...} /* Block about products on home page */

Of course, it’s possible in a local class to override one by one all styles inherited from a global class that has the same name, or just always invent local class names that are reliably unique and so are not conflicting with global ones.

But there is a more easy and right way: prepending local class names with a prefix that explicitly indicates their local purpose. Yours truly has chosen the underscore character as such prefix — it is neutral enough, demonstrable, and easy to use.

/* _derived is a modifier class */
.base._derived {...}

/* _local is a subordinate class in context selector */
.parent ._local {...}

/* _local is a subordinate class in child selector */
.parent > ._local {...}

It is appropriate to remark here that selecting HTML elements by multiple CSS classes at once is one of numerous great opportunities opening up thanks to dropping support for the old IE6 browser.

You may also be interested in resetting styles in CSS.