I stirred up some discussions the other day with a Twitter poll about :
.some-context .thing { /* special rules and overrides */ } Does that go in thing.css or some-context.css?
— Dave Rupert (@davatron5000) February 7, 2017
Of course everyone said “BEM does this”, except when you can’t control the classnames, which I can’t. The tweet also got some great responses and blog posts from CSS people I admire, who diverged from the poll.
- Harry Robert’s Code Smell in CSS Revisited
- Jonathan Snook’s CSS Coding for Context
Great posts from people who really think about good CSS architecture. These discussions inspired me to try something I’ve never done before with Sass partials and I’m currently enjoying the first fruits of this approach.
I’m working on a project where I’m redesigning a complex ecommerce organism that can appear within various contexts. Normally, I’d nest .somecontext > &
at the bottom of my _thing.scss
but this module is ~900 lines of code and needs to be broken up. So rather than littering .somecontext > .thing
overrides throughout my Thing partials, I created an thing/_in-somecontext.scss
partial that contains all my custom overrides.
My _thing.scss
looks like this:
// Responsive Choreography, Grids, Etc
@import 'thing/layout';
// Subcomponents
@import 'thing/header';
@import 'thing/preview';
@import 'thing/details';
// Contexts
@import 'thing/in-somecontext';
Inside thing/_in-somecontext.scss
looks something like this:
.somecontext {
.thing-header {
position:sticky;
}
.thing-preview {
display: none;
}
.thing-details {
font-size: 0.925rem;
}
}
In addition to separating concerns, it’s also really extensible to bundle these together. A new context? That’s just a new partial. If a context disappears, I can delete a single file. That’s great and feels true to the Single Responsibility Principle.
This hasn’t made it to production yet, so it’s possible it’ll change but I like the organization quite a bit.