画像の上に文字列を表示する方法
htmlとcssを使って、画像にマウスを置くと文字が出てくる部品の作り方を解説します。
今回javascriptは使用しません。また、scssも使いません。もちろんwebpackとかビルドは必要ないです。
最終的に↓のようなものを作れます。
htmlのコード
htmlのコードはこのようになっています。
<div> <div class="sp-image-wrap"> <img src="https://bulma.io/images/bulma-banner.png" alt=""> <span class="sp-description">Bulma is an open source CSS framework based on Flexbox and built with Sass. It's 100% responsive, fully modular, and available for free.</span> </div> <span>Bulma: a modern CSS framework based on Flexbox</span> </div>
imgのsrcにはサンプルとしてbulmaというcssフレームワークの画像を使っています。
今回の実装には関係ないですが、とても使いやすく、便利なコンポーネントが揃っています。
htmlでイメージ部分と、画像の下に出す文字列を分けています。
sp-description
をimgの上に表示されているように見せます。
cssのコード
cssの書き方はたくさんあると思いますが、ひとまずコードを載せます。
.sp-image-wrap { position: relative; } .sp-image-wrap:before { position: absolute; content: ''; background-color: #c3c3c3a3; top: 0; left: 0; width: 100%; height: 100%; visibility: hidden; z-index: -1; } .sp-image-wrap .sp-description { position: absolute; top: 0; bottom: 0; height: 100%; width: 100%; padding: 16px; overflow-y: scroll; visibility: hidden; z-index: -1; transform: translateY(-10px); transition: transform .3s ease; } .sp-image-wrap:hover img { filter: blur(5px); } .sp-image-wrap:hover:before { visibility: visible; z-index: 10; } .sp-image-wrap:hover .sp-description { visibility: visible; z-index: 11; transform: translateY(0px); }
機能を実装する上で工夫した点です。
sp-image-wrap
をrelative
にして、その子要素のsp-description
をabsolute
にしたhover
時に上から降りてくるようにtransform
とtransition
を設定したsp-image-wrap
のbefore
にオーバーレイを設定し、.sp-image-wrap:hover:before
とすることでhover時にbeforeを表示するようにした- そのままオーバーレイを表示すると、背景画像が残ってしまって見えづらいため
filter:blur
を使ってモザイク処理した display:none
を使うのではなく、アニメーションすることも考えてvisibility
を仕様した