cssだけで作る簡単なツールチップで、class名に方向を加えるだけで、表示位置を上、右、左、下に変更できます。次のボタン風サンプルは、オンマウスするとそれぞれテキストの表示位置の方向にツールチップを表示します。
<div class="wrapper"> <div class="tooltip top">表示位置 top</div> <div class="tooltip right">表示位置 right</div> <div class="tooltip left">表示位置 left</div> <div class="tooltip bottom">表示位置 bottom</div> </div>
.tooltip {
background-color: #f9c;
border-radius: 6px;
padding: 10px 15px;
position: relative;
margin: 15px;
text-align: center;
}
.tooltip::after {
background-color: #333;
border-radius: 6px;
color: #fff;
display: none;
padding: 10px 15px;
position: absolute;
text-align: center;
z-index: 999;
}
.tooltip::before {
background-color: #333;
content: ' ';
display: none;
position: absolute;
width: 15px;
height: 15px;
z-index: 999;
}
.tooltip:hover::after {
display: block;
}
.tooltip:hover::before {
display: block;
}
.tooltip.top::after {
content: 'top';
top: 0;
left: 50%;
-webkit-transform: translate(-50%, calc(-100% - 10px));
transform: translate(-50%, calc(-100% - 10px));
}
.tooltip.top::before {
top: 0;
left: 50%;
-webkit-transform: translate(-50%, calc(-100% - 5px)) rotate(45deg);
transform: translate(-50%, calc(-100% - 5px)) rotate(45deg);
}
.tooltip.bottom::after {
content: 'bottom';
bottom: 0;
left: 50%;
-webkit-transform: translate(-50%, calc(100% + 10px));
transform: translate(-50%, calc(100% + 10px));
}
.tooltip.bottom::before {
bottom: 0;
left: 50%;
-webkit-transform: translate(-50%, calc(100% + 5px)) rotate(45deg);
transform: translate(-50%, calc(100% + 5px)) rotate(45deg);
}
.tooltip.right::after {
content: 'right';
top: 0;
right: 0;
-webkit-transform: translateX(calc(100% + 10px));
transform: translateX(calc(100% + 10px));
}
.tooltip.right::before {
top: 50%;
right: 0;
-webkit-transform: translate(calc(100% + 5px), -50%) rotate(45deg);
transform: translate(calc(100% + 5px), -50%) rotate(45deg);
}
.tooltip.left::after {
content: 'left';
top: 0;
left: 0;
-webkit-transform: translateX(calc(-100% - 10px));
transform: translateX(calc(-100% - 10px));
}
.tooltip.left::before {
top: 50%;
left: 0;
-webkit-transform: translate(calc(-100% - 5px), -50%) rotate(45deg);
transform: translate(calc(-100% - 5px), -50%) rotate(45deg);
}