2017/04/05

inputやtextarea、buttonなどにfont-familyやfont-sizeが適用されないときの対処法

ウェブサイトを開発しているとき、なぜかinputタグやbuttonタグにfont-familyやfont-sizeで指定したスタイルが適用されなかった。他にもtextareaタグやselectタグ(ドロップダウンリスト)にも適用されなかった。

調べてみたところ、MDNに答えが載っていた。

フォントとテキスト
CSS のフォントやテキストの機能は、任意のウィジェットで容易に使用できます (また、フォームウィジェットで @font-face も使用できます)。ただし、ブラウザの動作にしばしば矛盾があります。デフォルトで、一部のブラウザは親から font-family や font-size を継承しません。代わりに多くのブラウザでは、システムのデフォルトの体裁を使用します。
HTML フォームへのスタイル設定 - ウェブ開発を学ぶ | MDN

どうやら、以下のスタイルを指定すれば良いらしい。
button, input, select, textarea {
  font-family : inherit;
  font-size   : 100%;
}


実際に違いを見る

<!-- index.html -->
<section id="sec01">
  <p>フォントとサイズが反映されない</p>
  <label for="name">Name</label>
  <input id="name" type="text" placeholder="firstname lastname">
  <textarea>textarea</textarea>
  <select>
    <option>select01</option>
    <option>select02</option>
    <option>select03</option>
  </select>
  <button>Button</button>
</section>

<section id="sec02">
  <p>フォントとサイズが反映される</p>
  <label for="name">Name</label>
  <input id="name" type="text" placeholder="firstname lastname">
  <textarea>textarea</textarea>
  <select>
    <option>select01</option>
    <option>select02</option>
    <option>select03</option>
  </select>
  <button>Button</button>
</section>

/* style.sass */
@import url("https://fonts.googleapis.com/css?family=Rokkitt");

html {
  font-family: "Rokkitt";
  font-size: 30px;
}
section {
  border: 1px solid black;
  margin: 10px;
  padding: 10px;
}

#sec01 {
  > * {
    display: block;
    margin: 10px 0;
  }
}
#sec02 {
  > input, textarea, select, button {
    font-family: inherit;
    font-size: 100%;
  }

  > * {
    display: block;
    margin: 10px 0;
  }
}


font-family: inherit を指定することで、親要素(上記の例ではhtmlで指定しているfont-family)をinherit(受け継ぐ、継承する)ことができる。

font-size: 100% で親要素のフォントサイズを基準として100%のサイズにできる(font-size: inheritという指定でもいける)



以上

written by @bc_rikko

0 件のコメント :

コメントを投稿