LoginSignup
11
9

More than 5 years have passed since last update.

よくあるコンポーネントの設計・実装パターン - ボタン編

Last updated at Posted at 2014-08-02

ボタン

button 要素でも、a 要素でも、div 要素でも、ボタンのコンポーネントとしての形を持たせることが出来るので、CSS のセレクタに要素を含め無いようにしましょう!

/* 好ましくない例 */
a.button,
button.button {
    display: inline-block;
    border: 1px solid #000;
    padding: 0.3em 1em;
    background-color: #eee;
    cursor: pointer;
}

button 要素

ブラウザ毎でデフォルトでスタイルを持っているものについては、reset.cssnormalize.css を当てても初期化しません。

1つの方法として、プロジェクト毎の冒頭、もしくは SMACSS で言うところの Base カテゴリ として、button 要素のデフォルトのスタイルを初期化します!

button 要素のセレクタに対して初期化を行うとユーザーエージェント独自のスタイルが使えなくなってしまうなど影響範囲が広いので、 ボタンコンポーネントに対してスタイルの初期化を行う記述を追加する方法 をとります!

/* button 要素そのものには何もしない */
button {}

/* ボタンコンポーネントに対してスタイルの初期化を行う */
.button {
    -webkit-appearance: none; /* 追加 */
       -moz-appearance: none; /* 追加 */
            appearance: none; /* 追加 */
    display: inline-block;
    border: 1px solid #000;
    margin: 0; /* 追加 */
    padding: 0.3em 1em;
    background-color: #eee;
    font-size: inherit; /* 追加 */
    cursor: pointer;
}

a 要素

デフォルトで下線やリンク色が設定されているので、デフォルトのスタイルを初期化します!
botton 要素同様、a 要素のセレクタに対して初期化を行うと様々なところで要素が使われている場合に影響範囲が広いので、上記スタイルの記述と合わせて ボタンコンポーネントに対してスタイルの初期化を行う 記述を追加します。

/* ボタンコンポーネントに対してスタイルの初期化を行う */
.button {
    -webkit-appearance: none;
       -moz-appearance: none;
            appearance: none;
    display: inline-block;
    border: 1px solid #000;
    margin: 0;
    padding: 0.3em 1em;
    background-color: #eee;
    text-decoration: none; /* 追加 */
    font-size: inherit;
    color: inherit; /* 追加 */
    cursor: pointer;
}

固定の幅を持たせない

ボーダーや背景色、padding の値はベースとなるスタイルを持てますが、幅については状況によって異なるため定義はしません。

例では、文字数によって幅が変わるようにしていますが デザイン設計上必ず固有の幅や最低限の幅を持つ ということであればベースとなるスタイルに含めてもよいかもしれません。

ボタンに固有の幅を持たせることが必要な状況だとしたら、対応方法の1つとして コンポーネントの Modifier を使って拡張する方法 があります。

.btn {
 
}
.btn--short {
    width: 200px;
}
.btn--long {
    width: 480px;
}
.btn--full {
    width: 100%;
}

しかしこれらは、バリエーションが増えた場合に命名に悩み続けることになります。この場合、 BEM でいうところの Block の Element として持たせるという方法 をとることが出来ます!

<div class="form">
    <div class="form__body"></div>
    <div class="form__footer">
        <button class="btn button--full">ログイン</button>
    </div>
</div>

<div class="comment">
    <div class="comment__body"></div>
    <div class="comment__footer">
        <button class="btn button--full">返信する</button>
    </div>
</div>
.form {
 
}
.form__footer {
    margin-left: auto;
    margin-right: auto;
    width: 200px; /* フォームにおけるボタンの幅 */
}

.comment {
    position: relative;
}
.comment__footer {
    position: absolute;
    right: 10px;
    bottom: 10px;
    width: 120px;
    font-size: 14px;
}
11
9
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
11
9