-
I got a question via DM, but prefer to answer these things where they can be useful to more people. In summary: "Why does everyone say not to use descendant selectors like
.sidebar .login {}
and instead combine things into classes like.login--sidebar
?" -
Part of the answer is that developers like being absolute about our rules 🙄 and don't like nuance. Ignore the rules. Descendant selectors are fine, and you should use them wherever you want. But the "rule" didn't appear out of nowhere. It likely traces back to OOCSS…
-
1. Styles based on location can be risky if you're working with components that might move around. Will they change in surprising ways when you move them? Only using classes on the component itself can help ensure that's controlled in one place. github.com/stubbornella/oocss/wiki#separate-container-and-content
-
In that case I would ask "is this really about the sidebar, or something else? What defines this variation?" It might be about available space, or the color palette, or…? If it's not really about the sidebar specifically, don't select it based on the sidebar.
-
2. Descendant selectors don't describe *ownsership* or *name-spacing*. Selecting "any title anywhere inside an article" is different from "The One Title of This Article". BEM classes & CSS-in-JS "scoped CSS" tools focus on that. So: article .title != .article_title
-
In my mind the more important rule is "selectors should say what you mean", and then the difficult work is really asking yourself "what do I mean in this case?"