Tooltips with html content

My WebDev Notes: How to create a tooltip with HTML and CSS

A tooltip is a common graphical user interface element found on some websites. It’s used to provide additional information to the user when they interact with a portion of text with their mouse or by touch. In this tutorial, you’ll learn how to create it with HTML and CSS.

The HTML

The tooltip text is contained within a portion of other text on a web page, most of the time, this text is a paragraph therefore, the HTML span tag is used to enclose it.

  class="tooltip"> Hover over me  class="tooltiptext">This is a tooltip  

The CSS

In the HTML above the tooltip text is part of the flow of the text which means when it’s rendered by the browser it will appear beside the text «Hover over me». The desired effect is to hide the text, and show it over the text Hover over me when the user interact with it. In order to achieve this, you have to hide the tooltip text; take it out of flow before you can position it over the text: Hover over me. First, you have to change the position property of the tooltip parent container to relative because when you take the tooltip text out of flow, you’ll have to position it relative to its parent and not the browser’s viewport. In addition, you’ll add a bottom border to serve as an indication that there is an information hidden from sight. Furthermore, the display property is changed to inline-block . This prevents the tooltip parent from spanning the entire browsers’ viewport.

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

Now, you can position the tooltip text. Since the parent container has a position relative , the tooltip text can have its position set to absolute . Therefore, you can use offset properties to accurately position it over the text Hover over me. Finally, you’ll like the tooltip text to appear over its parent text all the time, z-index takes care of this. The remaining styles are cosmetics.

.tooltip .tooltiptext  position: absolute; bottom: 125%; left: 50%; visibility: hidden; z-index: 1; /* Cosmetics */ color: #fff; background-color: #555; width: 120px; text-align: center; padding: 5px 0; margin-left: -60px; border-radius: 6px; opacity: 0; transition: opacity 1s; > 

In its current state, the tooltip is hidden, but before you write styles that will show it when the user interacts with it, you need to create a tiny indication that’ll show the user that the tooltip text belongs to the text Hover over me, sort of like when a human is holding a board which reads: I am human. In order to achieve this, you’ll use CSS pseudo-elements specifically ::after .

.tooltip .tooltiptext::after  /* Read on for the code and explanation */ > 

First, you set its content to empty, and change the position to absolute . Afterwards, you move the indicator to the center of the tooltip text and its parent text. Next, you use borders to create the indicators. Finally, when the user touches the text or mouse over it, you change the visibility and opacity to visible and 1 respectively.

.tooltip .tooltiptext::after  position: absolute; content: ""; /* Move it to the center */ top: 100%; left: 50%; /* This creates the indicators */ margin-left: -5px; border-width: 5px; border-style: solid; border-color: #555 transparent; > /** * Show the tooltip when you mouse over the * tooltip container */ .tooltip:hover .tooltiptext  visibility: visible; opacity: 1; > 

The completed tooltip is shown in the GIF below: You can check it online. The GitHub repo for this series:

ziizium / my-webdev-notes

Code snippets for series of articles on DEV about my experiments in web development

My WebDev Notes

This repositiory contains code snippets, and links for series of articles on DEV about my experiments in Web development.

List of articles

  • My WebDev Notes: CSS Loaders published on the 25 th February 2020
  • My WebDev Notes: Filter table published on the 1 st April 2020
  • MyWebDev Notes: Center page elements with CSS Grid published on the 3 rd of April 2020
  • My WebDev Notes: Photo gallery with CSS Grid published on the 7 th of April 2020
  • My WebDev Notes: Fullscreen overlay navigation published on the 13 th of April 2020
  • My WebDev Notes: A simple and accessible accordion published on 28 th of April 2020
  • My WebDev Notes: How to create a tooltip with HTML and CSS published on 3 rd February 2021
  • How to create a modal published on 22 nd June 2021

Источник

CSS Tooltip

A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element:

Basic Tooltip

Create a tooltip that appears when the user moves the mouse over an element:

Example

/* Tooltip text */
.tooltip .tooltiptext visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;

/* Position the tooltip text — see examples below! */
position: absolute;
z-index: 1;
>

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext visibility: visible;
>

Example Explained

HTML: Use a container element (like ) and add the «tooltip» class to it. When the user mouse over this , it will show the tooltip text.

The tooltip text is placed inside an inline element (like ) with class=»tooltiptext» .

CSS: The tooltip class use position:relative , which is needed to position the tooltip text ( position:absolute ). Note: See examples below on how to position the tooltip.

The tooltiptext class holds the actual tooltip text. It is hidden by default, and will be visible on hover (see below). We have also added some basic styles to it: 120px width, black background color, white text color, centered text, and 5px top and bottom padding.

The CSS border-radius property is used to add rounded corners to the tooltip text.

The :hover selector is used to show the tooltip text when the user moves the mouse over the with class=»tooltip» .

Positioning Tooltips

In this example, the tooltip is placed to the right ( left:105% ) of the «hoverable» text (). Also note that top:-5px is used to place it in the middle of its container element. We use the number 5 because the tooltip text has a top and bottom padding of 5px. If you increase its padding, also increase the value of the top property to ensure that it stays in the middle (if this is something you want). The same applies if you want the tooltip placed to the left.

Источник

Тултипы на CSS3 и HTML5

В связи с тем, что на Хабрахабре не нашёл я описания данного простого и в то же время удобного способа создания простых «тултипов» — всплывающих подсказок, я решил о нём написать.
В данном методе не будет использоваться JS, мы довольствуемся лишь CSS3 и HTML5.

Дисклеймер

На самом деле, css attr() для свойства псевдоэлемента content появился в CSS2 и в данном способе, в общем-то, нет ничего нового.

Простой способ

Здесь был пример

Этот способ сгодится там, где нужны небольшие «тултипчики» — всплывающие подсказки.

.tooltip < border-bottom: 1px dotted #0077AA; cursor: help; >.tooltip::after < background: rgba(0, 0, 0, 0.8); border-radius: 8px 8px 8px 0px; box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5); color: #FFF; content: attr(data-tooltip); /* Главная часть кода, определяющая содержимое всплывающей подсказки */ margin-top: -24px; opacity: 0; /* Наш элемент прозрачен. */ padding: 3px 7px; position: absolute; visibility: hidden; /* . и скрыт. */ transition: all 0.4s ease-in-out; /* Добавить плавности по вкусу */ >.tooltip:hover::after < opacity: 1; /* Показываем его */ visibility: visible; >

Мы берём некий элемент (В нашем случае span), добавляем к нему атрибут с текстом, который будет показан и берём псевдоэлемент ::after. В content этого псевдоэлемента мы, пользуясь замечательнейшим свойством attr(), присваиваем нашей всплывающей подсказке текст и потом по :hover показываем его.
Думаю, остальные свойства понятны по комментариям в коде.

Отдельно хочу отметить, как ведёт себя анимация в Chrome и Opera (Возможно и в IE, за его отсутствием проверить я не имею никакой возможности).
Её нет. Связано это с тем, что WebKit и Opera не применяют transitions и animation к псевдоэлементам ::before и ::after.
По этому поводу в багтрекере WebKit зарегистрирован баг.

Способ для более сложных тултипов

Иногда в тултипе должен быть не просто текст, но и некое форматирование или изображение, которое в предыдущий способ не вставишь.

Далее я рассмотрю лишь пример того, что можно сделать этим способом.

.htooltip span < /* Внешний вид нашего тултипа */ background-color: rgba(0,0,0, 0.8); border-radius: 15px 15px 15px 0px; box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.5); color: #fff; margin-left: 2px; margin-top: -75px; opacity: 0; /* Делаем его прозрачным */ padding: 10px 10px 10px 40px; position: absolute; text-decoration: none; visibility: hidden; /* И прячем */ width: 350px; z-index: 10; >.htooltip:hover span < /* По hover отображаем тултип */ opacity: 1; visibility: visible; >.htooltip span img < /* Изображение для примера */ border: 0 none; float: left; margin: -71px 0 0 -234px; opacity: 0; position: absolute; visibility: hidden; z-index: -1; >.htooltip:hover span img < /* Показываем изображение */ opacity: 1; visibility: visible; >

Всё просто. Данные примеры можно лицезреть на этой страничке.

P.S. Некоторые спросят: А где же HTML5? В статье упомянуты data-* атрибуты, являющиеся частью спецификации HTML5.

Источник

Tooltips with rich HTML content

Tooltips in amCharts 4 can display formatted information thanks to the style formatting and data binding syntax provided by built-in text formatter. However, sometimes we might go even further: use endless formatting possibilities provided by HTML and CSS. This tutorial will explain how.

Base chart

Let’s start with a pretty basic chart with multiple line series, a cursor, and a tooltipText set for the last series, that consolidates values from all three series in one tooltip.

series3.tooltipText = `[bold]YEAR [/] ---- Cars: Motorcycles: Bicycles: `; series3.tooltip.pointerOrientation = "vertical";
series3.tooltipText = `[bold]YEAR [/] ---- Cars: Motorcycles: Bicycles: `; series3.tooltip.pointerOrientation = "vertical";
< // . "series": [< // . >, < // . >, < // . "tooltipText": `[bold]YEAR [/] ---- Cars: Motorcycles: Bicycles: `, "tooltip": < "pointerOrientation": "vertical" >>] >

We get a nice consolidated tooltip once we hover through our chart:

NOTE Please note how we have set pointerOrientation to «vertical» . This will place our tooltip directly above the data point, as opposed to the side of it. This will be important in the later sections of this tutorial.

Making tooltip stick to all series

So far we have been adding tooltipHTML (or tooltipText ) to a single series, so that regardless of where your cursor is, the tooltip is always attached to a data item on that series.

That creates a problem when that particular series is hidden, e.g. via Legend.

In an attempt to fix that, we might try that we can add tooltipHTML (or tooltipText ) to every series. However, that would create another problem — instead of one tooltip we’d have several. Not good.

Luckily, we have a Cursor’s setting that will help us — maxTooltipDistance .

In a nutshell, it tells cursor to display tooltip only for the closest series and any other series that are within the pixel range of maxTooltipDistance .

Setting it to -1 will always force just a single tooltip.

chart.cursor.maxTooltipDistance = -1;
chart.cursor.maxTooltipDistance = -1;

Setting HTML content

There was some formatting applied to the SVG text above. But we want to go further and use whole power of HTML/CSS to format our stuff in the tooltip.

Lucky for us, it is possible.

If we set tooltipHTML instead of tooltipText , our tooltip will automatically display that content as HTML.

What’s even more cool, we can still use curly bracket placeholders to bind to the data:

series3.tooltipHTML = `
YEAR

Cars Motorcycles Bicycles

`;
series3.tooltipHTML = `
YEAR

Cars Motorcycles Bicycles

`;
< // . "series": [< // . >, < // . >, < // . "tooltipHTML": `
YEAR

Cars Motorcycles Bicycles

`, "tooltip": < "pointerOrientation": "vertical" >>] >

Congratulations! We now, we have a tooltip with full-fledged HTML in it:

NOTE Remember at the start of this article we mentioned pointer orientation was important? That was because of this interaction thing. Balloon is displayed for the data item that is under cursor. If the tooltip was displayed to the side, we’d try to hover button in it, move over to the next data item, which would cause tooltip to be moved and displayed for the new data item. This effectively would make our tooltip unhoverable.

Adding interactive elements

Now, let’s go crazy and add a button into our tooltip. Perhaps we want our users to be able to click on it for more information.

Since we already know contents of our tooltip is HTML, we can go ahead and add an tag and it will just work. Right?

We’ll just need to do one tiny thing. By default all interactions are disabled on tooltips, so that they do not obscure plot area. because of that, any interactive elements, such as buttons, in tooltip won’t work.

To fix that we’ll just go ahead and re-enable interactions on tooltip’s label which is accessible via label property:

series3.tooltip.label.interactionsEnabled = true;
series3.tooltip.label.interactionsEnabled = true;

Now, the button in our HTML will work.

And, what’s even more cool, the onclick events added to the button, will kick in just as well!

Try it on the live example below:

Limitations

That was all fine and nice. Now on to unpleasant stuff.

There are two limitations to the HTML-based tooltips.

  1. They will not work on Internet Explorer browsers (Edge is fine) and some other really old browsers. The tooltip will try to fall back to the SVG text on those browsers, so you might also want to set tooltipText as a means for alternative content.
  2. HTML content will not be exported to image formats. Normally, cursor is hidden (along with its tooltips) when exporting to images. However, if you have some jinga-majinga code that displays tooltip and relies on it to be exported to image, you’re in trouble.

Источник

Читайте также:  Games with python scripting
Оцените статью