AhmedRana
AhmedRana

Reputation: 503

Tooltip using css only

I have an application on which I can only change the CSS. e.g.

<p class="abc">My Text</p>

I can only change the abc in the above text or can add another css class along abc. Is there any way to display a tool tip by editing properties of abc in css? I can edit the css file only. Even the tool tip text have to be placed in css or the css can refer it from anywhere else. Any possibility?

Upvotes: 4

Views: 10240

Answers (2)

Aziz
Aziz

Reputation: 7793

Can it be done with pure CSS? Yes. However, with JavaScript you get much more control.

body { margin: 3em; }

.tooltip { position: relative; }

.tooltip::before {
  content: "\2003" attr(class); /* print em-space with class text */
  text-indent: -3.9em; /* add negative text offset to hide class name */
  display: inline-block;
  position: absolute; bottom: 50%;
  background: #000; color: #FFF; padding: 5px; border-radius: 5px;
  opacity:0; transition:0.3s; overflow:hidden;
  max-width: 50%; /* avoids very long sentences */
  pointer-events: none; /* prevents tooltip from firing on pseudo hover */
}

.tooltip:hover::before { opacity:1; bottom: 100%; }
<p class="tooltip Tooltip Text">My Text</p>
<p class="tooltip Dolor sit amet bla bla">Lorem Ipsum</p>

Basically I added an em space* and set a negative text-indent with overflow:hidden to hide the first part of text so that tooltip My Text here becomes My Text here. This is a bit hacky and you'll have to be careful of class name conflicts.

* The em-space is used to allow for some left padding.

jsFiddle: https://jsfiddle.net/azizn/gs1ye10r/2/

Upvotes: 9

mlegg
mlegg

Reputation: 832

Look at this page http://www.w3schools.com/css/css_tooltip.asp

.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;
    
    /* Position the tooltip */
    position: absolute;
    z-index: 1;
    bottom: 100%;
    left: 50%;
    margin-left: -60px;
}

.tooltip:hover .tooltiptext {
    visibility: visible;
}
<p>Move the mouse over the text below:</p>

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>

Upvotes: -3

Related Questions