Search code examples
htmlcssimagehovertooltip

Adding tooltip hover to an image with css


I want to create a tooltip (using css) that appears once the user moves the mouse over an element. I made it work for text, but I have problems making it work for an image.

.container {
  position: relative;
  width: 15%;
}

.image {
  position: relative;
  display: inline-block;
  width: 100%;
  height: auto;
}
.image .tooltiptext2 {
  visibility: hidden;
  width: 150%;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  top: -8px;
  left: 110%;
  font-size: 150%;
  font-family: Arial;

/* Fade in tooltip - takes 1 second to go from 0% to 100% opac: */
  opacity: 0;
  transition: opacity 1s;
}

.image .tooltiptext2::after {
  content: "";
  position: absolute;
  top: 50%;
  right: 100%;
  margin-top: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent black transparent transparent;
}
.image:hover .tooltiptext2 {
    visibility: visible;
    opacity: 1;
}

You can see what I did in this link:

https://jsfiddle.net/Ruloco/q3e4psh3/

I'll apreciate any help you could give me. Thanks in advance!!


Solution

  • .tooltiptext2 is not a child of .image. Using .image + .tooltiptext2 instead of .image .tooltiptext2 makes the tooltip work.

    https://jsfiddle.net/8Lmz2oLj/