Tooltips on Hover
Implement tooltips that appear when hovering over different elements, providing additional information.
Solution
- 1Item 1
- 2Item 2
- 3Item 3
Explanation
The HTML Structure
An unordered list
with list items
each with a span as the
.tooltip
The CSS
The list element
needs a relative position
. The tooltip
can then use position absolute
which will use the list container
as the parent.
As the span will now align all position values relative to the li element
.
In this example the positioning is off to the right with a -130px
from the right of the container.
Aligning vertically
To get a centrally aligned vertical height, you need a trick.
top: 50%
will move the span down relative to the top of itself. So you then have to translate
the span up by 50%
which moves it by 50% of it's own height.
Visibility vs Display
The visibility
attribute will keep the element in the HTML DOM structure where as the display
attribute adds or removes it from the DOM.
This is relevant because while both will work, you will get adverse effects in spacing as the structure could 'jump' around when using display
.
Code
import styles from "./Solution.module.css";
const Solution = () => {
return (
<div>
<ul>
<li className={styles.listItem}>
1<span className={styles.tooltip}>Item 1</span>
</li>
<li className={styles.listItem}>
2<span className={styles.tooltip}>Item 2</span>
</li>
<li className={styles.listItem}>
3<span className={styles.tooltip}>Item 3</span>
</li>
</ul>
</div>
);
};
export default Solution;
Styling
.listItem {
position: relative;
padding: 5px;
border: 1px solid black;
width: 50px;
text-align: center;
margin: 10px;
}
.tooltip {
position: absolute;
right: -130%;
top: 50%;
transform: translateY(-50%);
color: white;
background-color: grey;
padding: 5px;
border-radius: 5px;
visibility: hidden;
}
.listItem:hover .tooltip {
visibility: visible;
}