CSS Authoring Practices
Minimize specificity
A big part of maximizing composability is keeping CSS specificity low. Utility classes should always have a specificity score of 010
, or 020
if they require pseudo classes such as :hover
.
For component styles, aim to keep specificity scores for component to 010
or 020
whenever possible. Unless a component has an explicit dependency on a parent or child component (e.g. menus), its CSS should contain no references to other component classes.
Components styles should almost never use element selectors, as those unnecessarily increase specificity when chained with component classes or encode overly opinionated assumptions about composed elements when nested inside component classes. If an element rendered by a component needs to be targeted by a CSS selector, the element should be given a name and its own component class (see BEM naming conventions).
Follow BEM naming conventions for component styles
Follow a modified BEM naming convention for writing component class names (by modified, we just mean leveraging capitalization to clearly distinguish component classes from utility classes). The BEM mindset helps keep CSS specificity low, provides names to key elements within a component, and defines and communicates the relationships between those elements. Read more about naming conventions here.
info
Conditionally applying utility classes to components can be a powerful way to support various configuration use cases without adding additional CSS overhead, so not every styling concern needs to be handled via a BEM selector.
Fluid, not pixel perfect
Use em
values instead of pixels when specifying dimensions. Ems maintain proportional relationships between elements and ensure the interface scales proportionally in response to changes in the base font size (most notably, from user-supplied browser settings). Pixel values should only be used for design details like thin strokes and borders, where rendering fidelity relies on whole pixel values.
Reference CSS variables for design system styles
Reference CSS variables instead of hard-coding values for design details like colors, border radiuses, font weights, shadows, etc. This keeps those details in sync with the design system and maximizes the themability of your component out of the box.
Under Construction Notes
- Provide examples of "good" vs "bad" CSS practices