Frontend recipes RSCSS

Ever find yourself having a having a hard time maintaning your CSS? Finding no confidence whether a class name should be inside this parent or another? How should class names be named? Ha, got u fam. Good thing we follow a great CSS practice called RSCSS.

What is RSCSS?

RSCSS is your guideline in keeping your CSS maintainable. RSCSS heavily suggests in thinking in components. This way you can easily group the UI, making things reusable, easy to maintain, and easy to find.

We can easily visualize RSCSS with the following:

Components
  > Elements
  & Variants

We will be using the example below to demonstrate the idea of RSCSS.

Components

A component is the container encapsulating all the elements of the UI. They are named with at least two words, using dash as substitute to spaces.

In our example, we can refer to the pricing as .pricing-card. Always note that whenever you make components, make things descriptive and appropriate to the UI to easily identify them.

Other examples of components could be .search-bar, .inbox-row, or .dropdown-menu. Keep these other guidelines in mind:

  • Components are saved as its own file. (eg, css/components/pricing-card.scss)
  • Avoid making components deeper than 3 levels.

Elements

Elements are the things inside the component. In our example, this would be:

Elements are selected with the child combinator (>). In case the element has to be multiple words, combine it without using spaces or dashes.

.user-row
  > .firstname
  > .lastname

Always prefer to target class names and not the html tag as tags may not be descriptive.

Variants

Variants are the modifiers of your component or elements. They are usually used to change the look and behaviour of the component or element. Variants are prefixed with dashes (-) for easy identification. In the example, we could add the following:

Here are a few more examples:

.search-bar
  &.-ghost
  &.-expanded

.inbox-row
  &.-minimal
  &.-pinned

Notes

  • Avoid using IDs as selectors. Always use class names.

  • To easily identify if a thing should be a component, always think if it should stand on its own or not.

  • Ensure that components have meaning and can stand on its own. Elements, on the other hand, are usually neutral and vague on its own.

  • If you find your component exceeding 3 levels deep, extract some parts into smaller sub-components.

  • You can place components inside other components. In case you need to add variants to a nested component, place the variant inside the component it is adhering to and not to the parent component.

  • RSCSS is not a framework! It's an idea that can be implemented in many situations, and don't require any specific libraries to do so.

Resources

  • RSCSS (rscss.io) - Official site of RSCSS, including links to translations in different languages.