For a while now, I have been using a syntax similar to BEM in my projects. Recently, as I was revisiting some CSS articles, I came across this interesting read about the single responsibility principle:
https://i.sstatic.net/HdCXL.png
The concept discussed involves not only incorporating styles specific to the header__button
class into that particular class, but also relying on styles from the general button
class. This raises a question of whether we are creating a coupling between the element of header and the button
class. Essentially, any changes made to the button
class in the future would require careful consideration of all instances where it is being used.
While this approach may be justified in certain scenarios, such as maintaining consistent styles, how does it fare with more complex components like layout elements? Consider a situation where you have a Menu
class for arranging children vertically, and a Sidebar
class that also styles these children. The concern arises when both classes are utilized together:
menu.css
Menu {
}
Menu__item {
}
sidebar.css
Sidebar {
}
Sidebar__item {
}
index.html
<div class="Menu Sidebar">
<div class="Menu__item Sidebar__item">
</div>
<div class="Menu__item Sidebar__item">
</div>
</div>
If the positioning logic for items is solely contained within the Sidebar
class, any alterations to the code in the Menu
class could potentially disrupt the functionality of the Sidebar
class. Conversely, duplicating code across both classes violates the single responsibility principle. Lately, in my own projects, I have been leaning towards duplication in order to maintain separate responsibilities. Is this the best practice, though?