Good practices for writing component-based CSS (still a work in progress). Some practical examples, including folder structure, can be found in the Frontend Skeleton or in the CSS and HTML tags on this blog.
Stylesheets
I use BEM methodology for styles with the following naming convention:
.block {}
.block__element {}
.block__element--modifier {}
.block--block-modifier {}In SCSS it can be written as follows:
.block {
&__element {
&--modifier {}
}
&--block-modifier {}
}More informations about BEM can be found at BEM.info and GetBEM.com.
In addition to BEM, what has worked well for me is using prefixes inspired by the SMACSS architecture:
m-General prefix for modules that follows BEM methodology.is-,has-Indicates that some element is currently styled in a certain way because of a temporary, optional state or condition, e.g.is-active,is-hover,has-error.u-Utilities, mostly single responsibility classes or helpers.l-Layout rules can be used to override UI appearance based on a global state of a theme or a site.c-Component prefix, a specific piece of UI with a concrete purpose (e.g.c-navbar). You want to use it most of the time.o-An abstract, reusable object. It can be used as a building block for common patterns or elements (e.g. grid system). One have to be very careful when changing object classes, because they can have dependencies that are not obvious at first glance. If you have doubts, then probably it’s better to use a component instead of an object.s-Scope rules to define very specific context like the output from WYSIWYG editor or markdown, e.g.s-md-content(markdown content).js-Decouples JavaScript classes from CSS ones (separate an appearance from a functionality). For example with js-slider hook class we can apply slider functionality independently from module appearance:
<div class="m-slider js-slider"></div>
<div class="m-hero js-slider"></div>
<div class="m-carousel js-slider"></div>General good practices
- Keep selector specificity as low as possible, avoid nesting selectors and child selectors.
- Don’t use
!importantto solve specificity problems. - Don’t use tag names or IDs for styling.
- Use hex colors even in rgba, SCSS supports
rgba(#000, 0.2). - Use progressive enhancement and mobile first when possible.
- Define media queries in the same place as other rules to keep it clear how a current element behaves in all viewports, e.g:
.block {
&__element {
@media screen and (min-width: $screen-md-min) {}
@media screen and (min-width: $screen-lg-min) {}
}
}To be continued…
Share
Thanks for reading. If you liked it, consider sharing it with friends via:
Let's be in touch!
Don't miss other useful posts. Level up your skills with UX, web development, and productivity tips via e-mail.
