I am creating a solar system using CSS, and I want to display each planet’s name when the user hovers over it. However, I want to achieve this effect using only CSS, without JavaScript or additional attributes in the HTML (like data-name).
I've tried using ::before
to display the names, but I had to set the content property separately for each planet.
Here's my current CSS:
.planet {
position: absolute;
width: 60px;
height: 60px;
border-radius: 50%;
background-size: cover;
}
.planet::before {
content: "";
position: absolute;
top: -30px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 5px 10px;
font-size: 14px;
border-radius: 5px;
white-space: nowrap;
opacity: 0;
transition: opacity 0.3s ease-in-out;
pointer-events: none;
}
.planet:hover::before {
opacity: 1;
}
#earth:hover::before { content: "Earth"; }
#mars:hover::before { content: "Mars"; }
What is the best CSS-only approach to show planet names on hover? Is using ::before
the right method, or is there a more efficient technique?
As you seem to already have the ids set, you could use:
content: attr(id);
text-transform: capitalize;