LoginSignup
5
5

More than 5 years have passed since last update.

サイト内に詳細度の高いエリアが存在する場合のコンポーネントの書き方

Last updated at Posted at 2015-12-29

CSSには「スコープを切ると詳細度が増す」という厄介な問題が存在しているので、その対処方法について書きたいと思います。

スコープを切ると詳細度が増す例

記事系のサイトでありがちだと思いますが、

CSS
.entry-body h2 { ... }
.entry-body h3 { ... }
.entry-body li { ... }

これらは詳細度が0.1.1になっています。

問題となるコンポーネント

こちらもありがちなコンポーネントの例ですが、

HTML
<div class="your-component">
  <h2 class="your-component__title"> ... </h2>
  <ul class="your-component__items">
    <li class="your-component__item"> ... </li>
    <li class="your-component__item"> ... </li>
  </ul>
</div>
CSS
.your-component { ... }
.your-component__title { ... }
.your-component__items { ... }
.your-component__item { ... }

これらは詳細度が0.1.0なので、先ほどのスコープ内に配置されると衝突して厄介なことに。

詳細度が高いエリアにも対応できるコンポーネントの書き方

サポートブラウザがIE9以降なら、こう書けます。1

Stylus_or_Sass
.your-component

  :root &
    // ここに先頭要素のスタイルを記述

  :root &--mod
    // modifierがある場合

  & &__items
    // ここに子孫要素のスタイルを記述

  & &__item
    // ここに子孫要素のスタイルを記述

  &--mod &__item
    // modifierがある場合

  &--mod &--mod__item
    // modifier専用の子孫要素がある場合

詳細度はどれも0.2.0あるので、常にコンポーネント側が主導権を握れます。

おしまい

おまけ

morph.cssという、ちょっと斜め上を行くリセットCSSを作りました。

HTML
<div clas="your-component">
  <ul class="your-component__items div">
    <li class="your-component__item div">
      <a href="#" class="your-component__link span">

      </a>
    </li>
  </ul>
</div>

コンポーネントをセマンティックタグでガシガシ書いても、.divまたは.spanで即時に打ち消すことができます。

配布時の詳細度は0.1.0ですが、Stylusの利用で0.2.0に格上げできます。

Stylus
:root
  @import "/path/to/bower_components/morph.css/src/morph"

以上、告知でした


  1. IE8もサポートしたい場合は、:rootのところをhtml bodyにすれば0.1.1に勝てます。 

5
5
0

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
5
5