LoginSignup
28

More than 5 years have passed since last update.

csstyleを使ってcssのモジュール化を効率的に

Last updated at Posted at 2015-01-07

css、書くのがとてもむずかしいので、なんとかして綺麗に書いていきたいのですが、なにかと難しい事が多い。

BEMを使ってcssをモジュール化して管理するのが流行りなようですが、どうしてもBEMは人間の書くものじゃない気がしていました。

そんな中ちょっといいのではとおもったcsstyleというライブラリがあったので紹介します。

  • csstyleはsass3.3のfeatureを使っています。使用する場合はご注意ください。

csstyleって?

csstyleはとても簡単なsassのシンタックス拡張です。それ自体は80行ほどのとても小さなscssファイルなのですが、これによってcssがメンテナブルに、かつ綺麗に書けるというものです。

csstyleでは、cssを

  • components
  • options
  • parts
  • tweaks

という4つに分けて記述します。

(locationsというものもあるのですが、これは後述します)

BEM的には

componentsがblock、
optionsがmodifier、
elementがparts

というような対応になるでしょうか。(違っていたらごめんなさい)
これにtweaksというものが加わります。

tweaksはoptionsと同じようなものですが、optionsは一つのcomponentsにだけ適応するものなのに対し、tweaksはどのcomponentsにも適用できるようなもの、という感じです。

基本の使い方

実際に書いてみましょう。

まずはcomponentsから。(公式サイトから引用しています。一部わかりやすくするために変更しています)

<a class="button">Neat!</a>
@include component(button) {
  background: #6BD9ED;
  padding: 15px;
}

このように @include 文をつかってscssを記述し、それが button というクラス名でhtml内で使用できます。

つぎにoptions、partsを使ってみます

<a class="button --action">
  Register Now
  <span class="button__icon --hover"></span>
</a>

こんなhtmlがあったとして

@include component(button) {
  background: #6BD9ED;
  padding: 15px;

  @include option(action){
    color: #1F1F1F;
    background: #A7E040;
    padding-top: 0;
  }

  @include part(icon){
    font-size: 34px;
    position: relative;
    top: 10px;

    @include option(hover){
      color: red;
    }
  }
}

このように書いていきます。

tweaksは

<a class="button --action +rounded">
  Register Now
  <span class="button__icon --rocket"></span>
</a>
@include tweak(rounded) {
  border-radius: 10px;
}

このように +rounded といった形で記述できます。

また、locationというものもあり

<span class="@home">
  <a class="button --action +rounded +glass">
    Register Now
    <span class="button__icon --rocket"></span>
  </a>
</span>
@include location(home) {
  @include component(button){
    color: #6BD9ED;
    background: #1F1F1F;
  }
}

このように記述できます。

topページだけはデザインを少し変えたい、なんて時によいのかもしれないです。

まとめ

csstyleの良い所は、html側ではBEM記法でcomponentを記述することで、構造をわかりやすくする一方、css側ではBEMを書くこと無く、かつ可読性が高い状態でcssを記述できることかなと思います。

あとBEMをcssでもhtmlでも書くなんて正気の沙汰ではないと思うので、この方法はいいんじゃないかなぁと思っています。

公式サイト
Github

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28