css-modules-html-demo
css-modules-html-demo copied to clipboard
Block modifier affecting elements
Say you have .block___elem
and a .block--expanded
modifier. In BEM, to affect the elements with the block modifier:
.block--expanded .block__elem {
width: 100%
}
How are you supposed do to this in CSS modules? 😄
To be honest, I've stuck to plain CSS without any processing in my workflow. But I have some experience with this CSS Modules approach on some medium-sized projects.
Speaking of your example I'd write it using CSS Modules like that:
block.css:
.modifiedElement .element {
width: 100%;
}
This would be translated to:
.block__modifiedElement .block__element {
width: 100%;
}
Yeah, it's not 100% BEM-like. But the main principle, isolation of blocks, is still there.
Also, I had the following similar compound constructs:
header.css:
.root {
...
}
logo.css:
.headerRoot .image {
...
}
:global(html.is-foo) .element {
...
}
Ah, didn't know
.block__modifiedElement .block__element {
width: 100%;
}
would be the output, thanks! Do you know if this is the recommended approach? Or should all elements that should be modified have their state explicitly set? That would get boring pretty quick.
I've just realized the "modified" element is your example is a block itself. As far as I know CSS Modules doesn't have the concept of block-level stylesheets and it only works with elements. Therefore I had a convention to declare the block-level styles in the .root element on every block stylesheet. So the more accurate example would be:
block.css:
.root {
...
}
.expandedRoot {
...
}
.elem {
...
}
.expandedRoot .elem {
width: 100%;
}
index.html:
<% var block = require("./block") %>
<div class="${block.expandedRoot}">
<div class="${block.elem}"></div>
</div>
I'm not sure whether it's recommended by the CSS Modules authors or not, but it worked for me. And it wasn't bored me because I mostly had "modified" elements rather than "modified" blocks.