HOME > 開発者向けBLOG > Webデザイン >  input type textに表示するアイコンの位置

Technology Note 開発者向けBLOG

Webデザイン

input type textに表示するアイコンの位置

こんにちは、ゼノフィ渡部です。

input type textにアイコン表示する方法をご紹介いたします。

input type textに検索用のアイコンなどを表示する場合、input type text内に背景で表示する方法が浮かぶと思います。

表示することはたしかにできますが、IEブラウザの場合、検索文字が表示する領域にいっぱいになった場合、アイコンがずれて隠れてしまうか、文字がアイコンの上を素通りしてしまいます。

方法のひとつとして、input type textの外の要素の背景に表示させることで、アイコンの位置を常に同じ場所に表示させることができます。

2行目から6行目は、input type textの外の要素であるspanタグの背景でアイコンを表示させています。9行目から12行目は「search」というクラスでinput type text内にアイコンを表示させています。

1
2
3
4
5
6
7
8
9
10
11
12
/* アイコンを外の要素に表示 */
.radius span {
  display: block;
  padding: 0 0 0 25px;
  background: url(icon_search.gif) no-repeat 5px 2px;
}
 
/* input type text内に表示 */
.radius .search {
  padding-left: 25px;
  background: url(icon_search.gif) no-repeat 5px 2px;
}

HTMLは以下のように記述します。アイコンを同じ場所に表示するために、背景画像用の要素として、input type textの外にspan要素を記述しています。

1
2
3
4
5
6
7
8
9
10
11
<!-- アイコンを同じ場所に表示 -->
<p class="radius">
    <span>
        <input type="text" name="text" value="" maxlength="100" />
    </span>
</p>
 
<!-- アイコンが移動してしまう -->
<p class="radius">
    <input type="text" name="text" value="" maxlength="100" class="search" />
</p>

IE9、IE8、IE7、IE6で確認ができます。

サンプル

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
input {
  outline: none;
  background: none;
  appearance: none;
  -webkit-appearance: none;
  border-radius: 0;
  -webkit-border-radius: 0;
}
 
.radius {
  width: 289px;
  height: 19px;
  padding: 3px;
  background: url(item_bg_input.gif) no-repeat;
}
 
.radius input {
  width: 255px;
  height: 19px;
  border: none;
}
 
/* アイコンを外の要素に表示 */
.radius span {
  display: block;
  padding: 0 0 0 25px;
  background: url(icon_search.gif) no-repeat 5px 2px;
}
 
/* input type text内に表示 */
.radius .search {
  padding-left: 25px;
  background: url(icon_search.gif) no-repeat 5px 2px;
}

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- アイコンを同じ場所に表示 -->
<p>
    アイコンを同じ場所に表示。
</p>
<p class="radius">
    <span>
        <input type="text" name="text" value="" maxlength="100" />
    </span>
</p>
 
<!-- アイコンが移動してしまう -->
<p>
    アイコンが移動、または文字がアイコンの上を素通りしてしまう。
</p>
<p class="radius">
    <input type="text" name="text" value="" maxlength="100" class="search" />
</p>

PAGETOP