sgtpep / css-modules-html-demo

A demo of using CSS Modules within HTML files following the BEM-like approach and powered by Gulp and Lo-Dash/Underscore templates.
MIT License
22 stars 1 forks source link

Block modifier affecting elements #1

Open jeffijoe opened 8 years ago

jeffijoe commented 8 years ago

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? 😄

sgtpep commented 8 years ago

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 {
  ...
}
jeffijoe commented 8 years ago

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.

sgtpep commented 8 years ago

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.