Search code examples
jqueryhtmlcsstooltip

How can I create a responsive tooltip with just css3?


So I have a word in a paragraph that will have a tooltip.

<div>
  lorem 
  <div class="word">
    ipsum
    <div class="definition">this will be the tooltip text</div>
  </div> 
  blah blah blah
</div>

Right now using jQuery I set the definition element to be visible upon mouseover.

The word ipsum will be a dynamic word and the definition will be a dynamic set of words. I need to have definition be above ipsum while centered over the word ipsum with padding.

ipsum needs to be inline or inline-block so that the paragraph is undisturbed.

How can I get the definition element to be perfectly centered over the word ipsum with a dynamic size using only css?

I keep getting it centered over the left of the element or centered with the relative position, but it takes up space that it shouldn't in the word element.


Solution

  • Okay - this should work. It sets the left position of the .definition element to 50% of the parent's width and then the transform will move it back 50% of the .definition element's width.

    body {padding:50px} /* for demonstration */
    
    .word {
      display: inline-block;
      position: relative;
      background-color: lightyellow;
    }
    
    .definition { 
      display: none;
    }
    
    .word:hover > .definition {
      display: inline-block;
      position: absolute;
      bottom: 100%;
      left: calc(50%);
      transform: translateX(-50%);
      padding: 3px;
      border: 1px solid blue;
      white-space: nowrap;
    }
    <div>
      lorem 
      <div class="word">
        ipsum
        <div class="definition">this will be the tooltip text</div>
      </div> 
      blah blah blah
    </div>