LoginSignup
17
20

More than 5 years have passed since last update.

CSSのみで作る幅可変ツールチップ

Last updated at Posted at 2018-03-06

コード

HTML

<button>ボタン<span class="tooltip"><span class="text">テキスト</span></span></button>

CSS

button {
    position: relative;
}
.tooltip {
    visibility: hidden;
    text-align: center;
    position: absolute;
    z-index: 1;
    opacity: 0;
    transition: opacity 500ms;
    width: 120px;
    bottom: 125%;
    left: 50%; 
    margin-left: -60px;
}
.tooltip > .text {
    background-color: black;
    color: #fff;
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 12px;
    display: inline-block;
}
.tooltip > .text::after {
    content: " ";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: black transparent transparent transparent;
}
button:hover > .tooltip {
    visibility: visible;
    opacity: 1;
}

ポイントは.tooltipを幅固定にし、その中で幅可変な.textを置き、.textの方で背景色を設定するところです。

CSS Tooltipでは.tooltipに直接テキストを置いているため幅が固定されてしまい、短いテキストの場合大きな余白が生まれてしまいますが、上記のように外側(透過)と内側(テキスト+背景色)の2層構造にすればテキストの幅に合わせてツールチップの幅が決まります。

ツールチップの外側は以下のように幅を設定し、その半分の値の左マージンと、親要素の左半分の位置(水平方向の中心)を設定することでツールチップの中心と親要素の中心を合わせます。

.tooltip {
    width: 120px;
    left: 50%; 
    margin-left: -60px;
}

チールチップの矢印もCSSで描画します。


.tooltip > .text::after {
    content: " ";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: black transparent transparent transparent;
}

デモ

参考

17
20
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
17
20