alanbuchanan alanbuchanan - 6 months ago 32
CSS Question

Shorthand for class names targeted with regex

Due to the nature of using BEM in the project I am working on, I find myself and others using the following in our CSS files:

[class*="something"] { ... }
[class*="__something-else"] { ... }
[class*="--other-stuff"] { ... }
[class*="more-things"] { ... }
[class*="__even-more"] { ... }


Is there an advisable workaround to shorten the above to prevent tedious repetition of the word
class
, or should we stick by this method?

Answer

You need to use preprocessor like LESS or SCSS/Sass.

I use SCSS to demonstrate your idea.

By using @mixin and @content, you can create a class selector's generator function:

@mixin contain($name) {
  [class*=#{$name}] {
    @content;
  }
}

Create a new contain selector:

@include contain(--big) {
  font-weight: bold;
  font-size: 50px;
}

https://jsfiddle.net/twxia/pLy3bz44/2/

This seems not shorter than only typing [class*=...], but if you use Sass you can generate the @mixin like this:

+contain(--big)
  font-weight: bold
  font-size: 50px

I think use autocomplete plugin for editor or Sass will sovle your problem :D