この記事では、「画像の上にアイコンや文字、または画像を重ねて表示する方法」を紹介します。
まずは、次の画像をご覧ください。
この画像では、右下に「いいね」ボタンを表示しています。
この表現はCSSの“position: absolute”と”position: relative”を使うことで、実現できます。
アイコンや文字が載せられた画像を用意するのではなく、HTMLとCSSを使って表現することで、次のようなメリットが得られます。
- アイコンをクリックできるため、JavaScriptと組み合わせて使用できる
- アニメーション等の効果を設定できる
画像の上にいいねボタンを表示する
例として、いいねボタンを画像の上に表示する方法を説明したいと思います。
アイコンと画像を表示する
まず最初にアイコンと画像を表示します。
アイコンは”Font Awesome”を使って表示します。
HTMLは次のようになります。
<img src="画像.jpg"/>
<div>
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</div>
See the Pen 画像の上にいいねボタンを表示 – Part1 by aiiro (@aiiro29) on CodePen.
画像とアイコンが表示できました。まだ縦に並んで表示しているだけです。
いいねボタンを作成する
CSSでアイコンのデザインを変更します。
HTMLとCSSの内容は次のようになります。
HTML
<img src="画像.jpg"/>
<div class="good">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</div>
CSS
.good {
width: 50px;
height: 50px;
color: #ffffff;
background-color: #2779bd;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5rem;
border-radius: 50%;
cursor: pointer;
}
See the Pen 画像の上にいいねボタンを表示 – Part2 by aiiro (@aiiro29) on CodePen.
いいねボタンが用意できました。
次は画像の上にいいねボタンを表示していきます。
position:absoluteとposition:relativeを使って画像の上にボタンを重ねる
画像の上にいいねボタンを表示するためには、HTMLとCSSを編集する必要があります。
HTMLでは、画像タグとアイコンタグを囲むdivタグを用意します。
<div class="sample-box">
<img src="画像.jpg"/>
<div class="good">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</div>
</div>
.sample-box {
position: relative;
}
.good {
width: 50px;
height: 50px;
color: #ffffff;
background-color: #2779bd;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5rem;
border-radius: 50%;
cursor: pointer;
position: absolute;
top: 0;
left: 0;
}
画像タグといいねボタンのタグを囲むdivタグにクラスを設定し、そのクラスに”position: relative”を持たせています。
いいねボタンを表示するdivタグには、”position: absolute”と”top: 0″、”left: 0″を与えました。
See the Pen 画像の上にいいねボタンを表示 – Part3 by aiiro (@aiiro29) on CodePen.
画像の上にボタンが重なるようになりましたが、表示位置が左上になっています。
先程設定した”top: 0″と”left: 0″を変更して調整しましょう。
いいねボタンの表示位置を調整する
<div class="good">
には、”position: absolute”が付与されています。
absoluteが使われている場合は、”top, right, bottom, left”を使って位置を調整します。
.good {
width: 50px;
height: 50px;
color: #ffffff;
background-color: #2779bd;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5rem;
border-radius: 50%;
cursor: pointer;
position: absolute;
top: 80%;
left: 55%;
}

See the Pen 画像の上にいいねボタンを表示 – Part4 by aiiro (@aiiro29) on CodePen.
画像の上に画像を表示する
下記の内容は、画像の上に画像を表示するサンプルです。
アイコンの代わりに画像を表示するようになったことで、アイコンを表示するためのCSSが必要なくなっています。
それ以外は画像の上にアイコンを表示したのと同じ要領で、画像の上に画像を表示できます。
<div class="sample-box">
<img src="https://images.pexels.com/photos/1093946/pexels-photo-1093946.jpeg?auto=compress&cs=tinysrgb&h=350"/>
<div class="youtube">
<img src="https://img.icons8.com/color/50/000000/youtube-play.png">
</div>
</div>
.sample-box {
position: relative;
}
.youtube {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
position: absolute;
top: 80%;
left: 55%;
}
See the Pen 画像の上に画像を表示 by aiiro (@aiiro29) on CodePen.
まとめ
上記で紹介したように、”position: relative”と”position: absolute”を使うと、HTMLの要素を他の要素に重ねることができます。
|