Blog

検索フォームのbuttonやplaceholderにFont Awesomeを使う方法

2018.01.08 コーディング

非常に便利なアイコンフォント『Font Awesome』ですが、検索フォームのbuttonや入力欄のplaceholderにも使えてしまいます。

検索ボタンを虫メガネにしたりとかはよくあるデザインだと思うので、そんなときに画像を使わずに表現できます。

検索フォームのbuttonやplaceholderにFont Awesomeを使う方法

Font Awesomeを使う下準備

headにてFont Awesomeを読み込みます。

CDNを利用すればこちらでサーバーにFont Awesomeのファイルをアップロードせずにすぐ使えます。

新しいアイコンが追加されたときのメンテナンスも不要なのでおすすめです。

HTML
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

buttonにFont Awesomeのアイコンを表示するソース

検索フォームのボタンにFont Awesomeを使うソースです。

ボタンの場合は普通に<i>タグが使えます。CSSは適宜変更してください。

HTML
<div class="searchform">
<form method="get" action="http://xxxxxxxxxxxxx.com/">
<div>
  <input type="text" name="s" />
  <button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</form>
</div>
CSS
.searchform {
  background: #f99162;
  height: 65px;
  position: relative;
}

.searchform input[type=text] {
  width: 100%;
  height: 65px;
  border: 0;
  padding: 0 10px;
  background: #f99162;
  box-sizing: border-box;
}

.searchform button[type=submit] {
  border: 0;
  background: #f99162;
  width: 65px;
  height: 65px;
  line-height: 65px;
  text-align: center;
  position: absolute;
  top: 0;
  right: 0;
  font-size: 24px;
  color: #fdc28e;
}

placeholderにFont Awesomeのアイコンを表示するソース

次に、検索フォーム入力欄のplaceholderでFont Awesomeを使うソースです。

HTML
<div class="searchform">
<form method="get" action="http://xxxxxxxxxxxxx.com/">
<div>
  <input type="text" name="s" placeholder="" />
  <button type="submit">検索</button>
</div>
</form>
</div>
CSS
.searchform input[type=text] {
  height: 24px;
  border: 1px solid #d3d3d3;
  line-height: 26px;
  padding: 0 4px;
  font-family: FontAwesome;
}

.searchform ::-webkit-input-placeholder,
.searchform :-ms-input-placeholder,
.searchform ::-moz-placeholder {
  color: #d4d4d4;
}

.searchform button[type=submit] {
  height: 26px;
  line-height: 26px;
  background: #666;
  border: 0;
  color: #fff;
  padding: 0 10px;
  cursor: pointer;
}

CSSにてinput[type=text]のフォントファミリーをFont Awesomeに指定し、placeholderに使いたいアイコンのユニコードを入力します。

Font Awesomeのユニコードは、下記の参考ページで調べることができます。

まとめ

以上、検索フォームのbuttonやplaceholderにFont Awesomeを使う方法でした。

placeholderで使用する場合は、font-familyに指定した「FontAwesome」の後に他のフォントを指定すれば、検索フォームに入力した文字にはそちらが適用されるはずです(未検証)。