JavaScriptを一切使用せず、HTMLとCSSのみで構築されたシンプルで軽量なツールチップコンポーネントです。ホバー時に滑らかにフェードインし、対象の要素の上に表示されます。
以下のコードをコピーして、プロジェクトに貼り付けてください。
<!-- index.html -->
<div class="tooltip-wrapper">
<button class="tooltip-trigger">ホバーしてね</button>
<div class="tooltip-content">
これはピュアCSSツールチップです!
</div>
</div>/* styles.css */
.tooltip-wrapper {
position: relative;
display: inline-block;
}
.tooltip-trigger {
padding: 10px 20px;
border-radius: 8px;
border: none;
background-color: #3b82f6;
color: #fff;
cursor: pointer;
font-weight: bold;
transition: background-color 0.2s;
}
.tooltip-trigger:hover {
background-color: #2563eb;
}
.tooltip-content {
position: absolute;
bottom: 130%;
left: 50%;
transform: translateX(-50%) translateY(10px);
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
background-color: #1f2937;
color: #fff;
padding: 8px 12px;
border-radius: 6px;
font-size: 14px;
white-space: nowrap;
z-index: 10;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
/* 下向きの三角形(矢印) */
.tooltip-content::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -6px;
border-width: 6px;
border-style: solid;
border-color: #1f2937 transparent transparent transparent;
}
/* ホバー時の動作 */
.tooltip-wrapper:hover .tooltip-content {
opacity: 1;
visibility: visible;
transform: translateX(-50%) translateY(0);
} position: relative と position: absolute: `tooltip-wrapper` に `relative` を指定することで、ツールチップ本体 (`tooltip-content`) を親要素を基準に絶対配置 (`absolute`) します。