Tooltip hiển thị phía trên (Top Tooltip)
Để tooltip xuất hiện **phía trên** phần tử cha, đặt tooltip ở `bottom: 100%` (dưới cùng cha = trên cùng tooltip) và căn giữa ngang bằng `left: 50%` + `transform: translateX(-50%)`.
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html>
<head>
<style>
.mytooltip .mytext {
visibility: hidden;
width: 140px;
background-color: blue;
color: #fff;
z-index: 1;
bottom: 100%; /* Dưới cùng tooltip = trên cùng cha */
left: 50%; /* Căn giữa ngang */
margin-left: -70px; /* Nửa width (140/2) - cách cũ */
/* Hoặc hiện đại: */
/* left: 50%; transform: translateX(-50%); */
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
}
.mytooltip {
position: relative;
display: inline-block;
margin-top: 50px; /* Khoảng cách top trang để tooltip không bị tràn */
}
.mytooltip:hover .mytext {
visibility: visible;
}
</style>
</head>
<body>
<div class="mytooltip">
Keep mouse cursor over me
<span class="mytext"> My Tooltip text</span>
</div>
</body>
</html>
Cải tiến hiện đại (Recommended)
.mytooltip .mytext {
/* ... */
bottom: calc(100% + 8px); /* 100% height cha + gap 8px */
left: 50%;
transform: translateX(-50%); /* Căn giữa chính xác, không cần margin-left */
opacity: 0;
transition: opacity 0.2s, visibility 0.2s;
}
.mytooltip:hover .mytext {
visibility: visible;
opacity: 1;
}
/* Mũi tên trỏ xuống */
.mytooltip .mytext::after {
content: "";
position: absolute;
top: 100%; /* Đính dưới tooltip */
left: 50%;
transform: translateX(-50%);
border-width: 6px;
border-style: solid;
border-color: blue transparent transparent transparent;
}
So sánh 4 vị trí tooltip
| Vị trí | Tooltip Position | Arrow Position |
|---|---|---|
| Top | bottom: 100%; left: 50%; transform: translateX(-50%); | top: 100%; border-top-color |
| Bottom | top: 100%; left: 50%; transform: translateX(-50%); | bottom: 100%; border-bottom-color |
| Left | top: 50%; right: 100%; transform: translateY(-50%); | right: 100%; border-right-color |
| Right | top: 50%; left: 100%; transform: translateY(-50%); | left: 100%; border-left-color |