Text when hover css

:hover

Хорошим паттерном в сайтостроении считается реакция элементов на действия пользователя. Например, если на элемент можно нажать, то при наведении курсора его стили должны немного меняться, как бы говоря пользователю «Нажми меня!»

Раньше интерактив можно было реализовать только при помощи JS, что сильно усложняло верстальщикам жизнь. Но сегодня у нас существует отличный помощник — псевдокласс :hover .

Пример

Скопировать ссылку «Пример» Скопировано

Ссылка в спокойном состоянии будет чёрного цвета и без подчёркивания, а при наведении курсора мыши сменит цвет на розовый, и у неё появится подчёркивание. Пользователь поймёт, что это интерактивный элемент, с которым можно взаимодействовать.

 .link  color: #000; text-decoration: none;> .link:hover  color: pink; text-decoration: underline;> .link  color: #000; text-decoration: none; > .link:hover  color: pink; text-decoration: underline; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

После любого селектора ставим двоеточие и пишем ключевое слово hover .

Селектор по тегу в состоянии :hover

Скопировать ссылку «Селектор по тегу в состоянии :hover» Скопировано

 a:hover  /* Стили */> a:hover  /* Стили */ >      

Селектор по классу в состоянии :hover

Скопировать ссылку «Селектор по классу в состоянии :hover» Скопировано

 .link:hover  /* Стили */> .link:hover  /* Стили */ >      

Составной селектор в состоянии :hover

Скопировать ссылку «Составной селектор в состоянии :hover» Скопировано

 li .link:hover  /* Стили */> li .link:hover  /* Стили */ >      

Селектор по id в состоянии :hover

Скопировать ссылку «Селектор по id в состоянии :hover» Скопировано

 #id:hover  /* Стили */> #id:hover  /* Стили */ >      

Селектор по классу и его псевдоэлемент в состоянии :hover

Скопировать ссылку «Селектор по классу и его псевдоэлемент в состоянии :hover» Скопировано

 .link::before:hover  /* Стили */> .link::before:hover  /* Стили */ >      

Как понять

Скопировать ссылку «Как понять» Скопировано

Браузер подставляет любому элементу, на который наводится курсор, пометку в виде автоматически создаваемого класса. Мы можем стилизовать этот класс на своё усмотрение, при этом сама логика и механизм отслеживания наведения курсора будут скрыты под капотом движка браузера.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 :hover можно очень круто анимировать, добавив в блок кода свойство transition 🎉

💡 На наведения курсора может реагировать абсолютно любой элемент, необязательно ссылка или кнопка.

💡 Если дизайнер не нарисовал в макете разные состояния, либо просите у него это сделать, либо пропишите стили на своё усмотрение. Но любой элемент, на который можно нажать, должен иметь как минимум стили для :hover .

На практике

Скопировать ссылку «На практике» Скопировано

Дмитрий Волков советует

Скопировать ссылку «Дмитрий Волков советует» Скопировано

💡 А что если на сайт зайти с планшета, к которому подключена bluetooth-мышь? Однозначно, ховер должен работать! А если дополнительных устройств ввода нет, то, конечно, стили по наведению должны быть сброшены, чтобы избежать визуального залипания при нажатии на соответствующие элементы.

Вот удобная практика для таких случаев, она ещё и позволяет писать чуточку меньше кода.

🛠 Чтобы не писать дополнительные обнуления ховер-стилей для тач-устройств, состояние :hover удобно задавать внутри медиавыражений с условием по типу взаимодействия с устройством.

Пример, исключающий тач-устройства, но не полностью:

 .link  color: #ffffff; text-decoration-color: #2E9AFF; transition: background-color 0.5s linear;> /* Есть возможность навести указатель на элемент */@media (any-hover: hover)  .link:hover  background-color: #2E9AFF; transition: background-color 0.1s linear; >> .link  color: #ffffff; text-decoration-color: #2E9AFF; transition: background-color 0.5s linear; > /* Есть возможность навести указатель на элемент */ @media (any-hover: hover)  .link:hover  background-color: #2E9AFF; transition: background-color 0.1s linear; > >      

Условие any — hover : hover допускает устройства с сенсорным экраном, но только если подключено дополнительное устройство ввода с нужной функциональностью для ховера (мышь, тачпад и т. п.)

Таким образом, мы успешно задали стили по наведению на ссылку, которые не будут учтены на мобильных устройствах, но заработают, если имеется курсор.

По аналогии можно использовать и другое состояние — :active .

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 Пользователь может зайти на ваш сайт не только с десктопа, где есть мышка и её можно на что-то навести, но и с планшета или телефона, где мышкой выступает палец, а его нельзя на что-то навести, им можно только тапнуть.

Хорошая практика — сбрасывать :hover стили для тач-устройств. Иначе при нажатии на какой-то элемент ховер-стили будут залипать — телефон не знает, когда вы отводите палец в сторону.

🛠 Сайт смотрится аккуратнее и интереснее, если изменение стилей происходит с лёгкой анимацией, а не резко. Этот принцип взят из окружающего нас мира. Вспомните хоть одно событие, которое происходит резко, моментально, без промежуточных стадий. Не вспомните 😏

Я в своей работе стараюсь делать анимацию стилей для наведения по принципу «появляется быстро, пропадает медленно». Это позволяет пользователю быстро увидеть реакцию на свои действия и не дожидаться окончания анимации.

 .link  color: #ffffff; text-decoration-color: #2E9AFF; /* Скорость исчезновения фонового цвета */ transition: background-color 0.5s linear;> .link:hover  background-color: #2E9AFF; /* Скорость изменения фонового цвета на голубой */ transition: background-color 0.1s linear;> .link  color: #ffffff; text-decoration-color: #2E9AFF; /* Скорость исчезновения фонового цвета */ transition: background-color 0.5s linear; > .link:hover  background-color: #2E9AFF; /* Скорость изменения фонового цвета на голубой */ transition: background-color 0.1s linear; >      

Ссылка быстро (за 0.1 секунды) меняет фоновый цвет на голубой при наведении курсора и чуть медленнее (за 0.5 секунды) приходит обратно в исходное состояние, когда курсор уводится за пределы ссылки.

🛠 Если вы задаёте стили для разных состояний ссылок, то следует придерживаться определённого порядка в объявлении стилей: :link — :visited — :focus — :hover — :active .

Этот порядок легко запомнить в виде аббревиатуры LVFHA и мнемоники LoVe Fears HAte.

Источник

How to create hover text using HTML and CSS

Last Updated Jul 03, 2022

A hover text (also known as a tooltip text) is used to display additional descriptions over an HTML element. The text only appears when the mouse cursor hovers over an object.

  • Adding the global title attribute for your HTML tags
  • Creating a tooltip CSS effect using :before selector

This tutorial will show you how to use both methods.

Let’s start with learning how to create a hover text by adding the title attribute to your HTML elements.

Create hover text by adding the title attribute

The global title attribute is an attribute that you can add to any valid HTML tag to provide extra information about the element being rendered by the tag.

For example, the following title attribute is being added to both and tags:

 You can see a small hover text shown when the mouse hovers over the elements below:

As you can see from the example above, the title attribute will be shown when the user hovers over the rendered elements using the mouse. You can add the title attribute to any valid HTML element.

The hover text created from the title attribute is set by the browser, which means you can’t customize the style of the display.

If you want a better looking hover text, then you need to create your own using CSS.

Create a hover text using HTML and CSS :before selector

The CSS :before selector creates and inserts a pseudo-element before the content of the selected element, which is perfect for adding a hover text effect for your HTML elements.

To create a hover text using HTML and CSS, you need to group the display text and the hover text in one container element first:

 The example above puts the hover text inside the data-hover attribute, replacing the need to use the title attribute to store the hover text.

Now you need to add CSS style to hide the hover text. The following CSS will do the trick:

The content of the hovertext:before element will be derived from the data-hover attribute as specified in the selected element.

First, the position property of the .hovertext:before selector is set to absolute so that it can be displayed outside of the document flow.

The absolute element will be positioned relative to the closest container tag with the position:relative value.

This is why the .hovertext position property is changed to relative so that the .hovertext:before will be placed relative to the .hovertext element.

Next, the visibility of the .hovertext:before is set to hidden to hide the text. The visibility will be changed to visible when the user hovers over the .hovertext element.

  • A one second transition for the opacity of the .hovertext element is added to improve the aesthetic of the hover text
  • The z-index is set to 1 so that the hover text appears above the other text
  • The top and left property displays the edges of the hover text element

The resulting hover text will be as shown below:

By wrapping the hover text using the tag, you can place the element inside a

or a tag:

Finally, you can also dynamically resize the hover text label according to the size of your content.

To do so, you need to use max-content as the value of the width property in the .hovertext:before rule.


And that’s how you can create hover text using CSS and HTML. You can customize the CSS style above as you need.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to Add a Mouseover Text with HTML

It is possible to add a mouseover text description without Javascript and even without CSS. Let’s see how we can do this by using only HTML.

Solutions with HTML

To add a text on hover, you’ll need to use the title attribute. In this snippet, we'll use it on the , , , and elements.

Before starting, be sure to use the latest version of your Internet browser.

Example of adding a text on hover with the element:

html> html> head> title>Title of the document title> head> body> h2>Example h2> div title="This is a mouseover text!">Hover this text to see the result. div> body> html>

Result

Example of adding a text on hover with the element:

html> html> head> title>Title of the document title> head> body> h2>Example h2> span title="Hello world!">Hover this text to see the result. span> body> html>

Example of adding a text on hover with the and

elements:

html> html> head> title>Title of the document title> head> body> h2>Example h2> abbr title="Hypertext Markup Language">HTML abbr> p title="Hello world">Hover this one p> body> html>

You can add hover text (also known as a tooltip) to a link in HTML using the title attribute. The title attribute specifies extra information about an element, and is displayed as a tooltip when the user hovers over the element.

Here's an example of how to add hover text to a link:

html> html> head> title>Title of the document title> head> body> h2>Example h2> a href="https://w3docs.com" title="Click to visit W3docs.com">W3docs a> body> html>

You can customize the hover text to be whatever you want, and you can apply this technique to any HTML element that supports the title attribute.

The 'title' attribute is a standard HTML attribute that is supported by all modern web browsers, including Chrome, Firefox, Safari, Opera, and Edge. It is also supported by older browsers, going back to at least Internet Explorer 6.

However, it's worth noting that some assistive technologies, such as screen readers, may not announce the title attribute by default, and some users may have disabled the display of tooltips in their browser settings. As a result, it's generally recommended to use the title attribute sparingly, and to provide any important information in the content of the page itself, rather than relying solely on tooltips.

Источник

Читайте также:  Изменения html при помощи js
Оцените статью