【HTML/CSS】ボタンに画像を表示する

プログラミング
スポンサーリンク

何がしたいの?

画像ボタンを用意したい
imgタグにクリックイベントつけても良いが、
ボタンとして使うなら、ちゃんとボタンタグを使いたいよね!

実装!

<input type="button" class="image-button" style="background-image: url('./search.svg');" />
<input type="button" class="image-button" style="background-image: url('./save.svg');" />
<input type="button" class="image-button" style="background-image: url('./edit.svg');" />
<input type="button" class="image-button" style="background-image: url('./delete.svg');" />
<p>

<input type="button" class="image-button image-button-text" value="検索"     style="width: 120px; background-image: url('./search.svg');" />
<input type="button" class="image-button image-button-text" value="保存TEST" style="width: 150px; background-image: url('./save.svg');" /><br />
<input type="button" class="image-button image-button-text" value="編 集"   style="width: 180px; background-image: url('./edit.svg');" />
<input type="button" class="image-button image-button-text" value="削 除"   style="width: 100px; background-image: url('./delete.svg');" /><br />
.image-button {
	border: solid 1px gray;
	
	border-radius: 5px;
	background: none;
	background-repeat: no-repeat;
	background-size: auto 85%;
	background-position: center center;
	width: 30px;
	height: 30px;
	
	text-align: left;	/* テキストは左寄せ */
	text-indent: 30px;	/* インデントを使用して画像分余白を開ける */
}

.image-button:hover {
	background-color: lavender;
	background-size: auto 90%;
}
.image-button:active {
	background-color: #DFDFF9;
	background-size: auto 80%;
}

.image-button-text {
	background-position: center left 5px;	/* 上下中央/左から5pxの位置 */
}

解説

画像は、ボタンごとに別のものを使うことが多いと思う。
保存系ならフロッピー、編集なら鉛筆とか。

そのため、background-image だけはCSSで指定せず、
タグのstyle属性に直接指定することで、共通化している。

また、システム全体で統一したデザインにするため、
基本的なサイズはCSSに記載しているが、
文字列も表示したいときなどはstyle属性で別途サイズを指定する。

文字列をボタンに表示する場合、中央に画像があると邪魔になるので、
その場合だけ別のクラスを追加してあげることで、
画像の左寄せをしている。
クラスを指定する順序が入れ替わると破綻ので注意。。。

サンプル

ごめんなさい。。。
いつかサンプル追記します(´・ω・`)

コメント

タイトルとURLをコピーしました