【CSSのみで作れる】ツールチップの簡単な実装方法


概要

カーソルを合わせると出てくるツールチップを作成する。CSSのみで作れるらしい。またスマホ(タッチデバイス)を考慮した実装。
ちなみにツールチップってのは下みたいにカーソルを合わせるとヒントが出てくるヤツ。

実装例

詳細

擬似クラスを組み合わせるとPCとスマホ両方に対応できます。

PC

カーソルを合わせるとツールチップがでる。擬似クラスである
:hover
で対応。

スマホ(タッチデバイス)

触るとツールチップがでる。擬似クラスである
:focus
で対応。

実装

骨組み

最低限の実装をすると、

HTML
詳しくは
<a href="#" class="tooltip" aria-label="これはツールチップの例です。">
    ヒント
</a>
をご覧ください。
Scss
@mixin not-custom() {
  content: attr(aria-label);
  display: block;
  position: absolute;
}

.tooltip {
  position: relative;
  color: goldenrod;
  display: inline-block;

  &:focus {
    &:after {
      @include not-custom();
    }
  }
  &:hover {
    &:after {
      @include not-custom();
    }
  }
}

attr()の使い方...

結果

マウスを合わせると...

って感じ大枠は完成。

体裁を整える

体裁用の共通mixinを作る。(mixinじゃなくていいけど)

Scss
/*体裁カスタマイズ*/
@mixin custom() {
  top: 100%;
  left: -25%;
  font-size: 1.2rem;
  background-color: #4e4e4e;
  color: #fff;
  margin-top: 0.8rem;
  border-radius: 0.2rem;
  padding: 0.4rem;
  width: 12rem;
  text-align: left;
}

作ったmixinをincludeする。

Scss
.tooltip {
  position: relative;
  color: goldenrod;
  display: inline-block;

  &:focus {
    &:after {
      @include not-custom();
      //追加
      @include custom();
    }
  }
  &:hover {
    &:after {
      @include not-custom();
      //追加
      @include custom();
    }
  }
}

おまけでbodyも整える。

Scss
/*体裁カスタマイズ*/
body {
  padding: 4rem;
  text-align: center;
  font-size: 2rem;
}

結果

マウスカーソルを合わせると...

良い感じや!

矢印も添える

三角矢印はcssのみで作れる。

Scss

/*三角ができる*/
@mixin arrow() {
  position: absolute;
  display: block;
  content: "";
  top: 100%;
  right:0;
  left: 0;
  margin: -1rem auto 0;
  border: 1rem solid transparent;
  border-bottom-color: #4e4e4e;
  height: 0;
  width: 0;
}

tooltipクラスのbeforeに追加してやる。

Scss

.tooltip {
  position: relative;
  color: goldenrod;
  display: inline-block;

  &:focus {
    //追加
    &:before {
      @include arrow();
    }
    &:after {
      @include not-custom();
      @include custom();
    }
  }
  &:hover {
    //追加s
    &:before {
      @include arrow();
    }
    &:after {
      @include not-custom();
      @include custom();
    }
  }
}

結果

矢印(三角)がで装飾されました。完成です。