Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 23, 2021 03:31 am GMT

Setup a HTML tooltip on hover using CSS

Tooltips are little boxes containing helpful text that appear when you hover over certain elements in a web page. Theyre a useful UI component for providing additional information to users without having to clutter the interface. In this tutorial well be creating a simple tooltip using HTML & CSS with no JavaScript required.

Let get started with the HTML markup:

<p>Example CSS Tooltip <span data-tooltip="Tooltips are used to provide information about an element on a web page.">i</span></p>

The tooltip will appear when we hover over the <span> element displaying the text from the data attribute. Alternatively you could apply the data attribute to a hyperlink or button and the tooltip will function the same way.

Now for the CSS starting with the tooltips trigger element:

[data-tooltip] {  position: relative;  cursor: pointer;  background: black;  color: white;  font-size: 12px;  border-radius: 1em;  padding: 0 0.5em;}

As were using a data attribute we can use the CSS [attribute] selector which selects all elements with a specified attribute (data-tooltip). The actual tooltip that appears on hover will be constructed using :before and :after pseudo elements:

[data-tooltip]:before {  content: attr(data-tooltip);  position: absolute;  opacity: 0;   width: 150px;  transform:translateX(-50%);  bottom: 25px;  padding: 0.5em;  background-color: black;  border-radius: 0.25em;  color: white;  text-align: center;  transition:0.2s;}

Next well a small arrow shape so the tooltip looks like a speech bubble:

[data-tooltip]:after {  content: "";  position: absolute;  opacity: 0;   bottom: 15px;    margin-left: -5px;   border: 5px solid black;  border-color: black transparent transparent transparent;  transition:0.2s;}Code language: CSS (css)Finally we need to set the opacity to be visible when the tooltip element is hovered:[data-tooltip]:hover:before,[data-tooltip]:hover:after {  opacity: 1; }

Thats all for this tutorial, weve just created a animated tooltip using only HTML and CSS. The only drawback when creating tooltips using this method is data attributes dont support hyperlinks so these tooltips are unable to contain links and are purely text only.


Original Link: https://dev.to/michaelburrows/setup-a-html-tooltip-on-hover-using-css-23b3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To