1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ホバー時に文字をオーバーレイで表示させるエフェクトをdata属性を使って実装

Posted at

0331.gif
↑このように画像にホバーしたら文字がふわっと出てくるエフェクトをdata属性と疑似要素を使って実装してみました。

data属性(data-○○)に出したい文字列を入れる

html
<div class="wrapper">
  <div class="box" data-hover="ほげほげ">
    <img src="https://picsum.photos/id/237/300/300">
  </div>
  <div class="box" data-hover="ふがふが">
    <img src="https://picsum.photos/seed/picsum/300/300">
  </div>
  <div class="box" data-hover="ぴよぴよ&#13;&#10;改行">
    <img src="https://picsum.photos/id/1084/300/300">
  </div>
</div>

ここではdata-hoverとしていますがdata-に続く文字列はわかりやすい任意のものでOKです。
改行したい場合は&#13;&#10;と入れて、cssでwhite-space: pre;を指定します。

疑似要素のcontent: attr(data-○○);で出力

css
 /* 横並びのくだりは省略 */

.box {
  position: relative;
}

.box > img {
  width: 100%;
  position: relative;
  z-index: 1;
  vertical-align: bottom;
}

.box::before {
  content: attr(data-hover); /* data-hoverの値を表示 */
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: opacity 0.3s;
  color: #fff;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  line-height: 2;
  white-space: pre; /* これがないと改行が効かない */
  z-index: 3;
}

.box::after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 2;
}

.box:hover::before {
   opacity: 1;
}

.box:hover::after {
  opacity: 0.5;
}

コード全文はこちら

See the Pen hoverしたらdataの文字を出す by sogawa-BitStar (@sogawa-BitStar) on CodePen.

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?