Тег DIV, атрибут title

add title attribute from css

For anyone reading this in the future, you can create custom tooltips with CSS using pseudo elements you can either specify the text value in a custom data-* attribute or the content property. See this answer — stackoverflow.com/questions/1055581/…

8 Answers 8

Well, although it’s not actually possible to change the title attribute, it is possible to show a tooltip completely from CSS. You can check a working version out at http://jsfiddle.net/HzH3Z/5/.

What you can do is style the label:after selector and give it display:none, and set its content from CSS. You can then change the display attribute to display:block on label:hover:after, and it will show. Like this:

label::after < content: "my tooltip"; padding: 2px; display: none; position: relative; top: -20px; right: -30px; width: 150px; text-align: center; background-color: #fef4c5; border: 1px solid #d4b943; -moz-border-radius: 2px; -webkit-border-radius: 2px; -ms-border-radius: 2px; border-radius: 2px; >label:hover::after

+1, you can even use data attributes as the source for the tooltip. Example fiddle. (This way your content remains in HTML, and your CSS again only is used to tell the browser how to show it).

This should be the accepted answer. The question was, essentially, how can I add a tooltip using css? This answers it the best.

I would avoid this sort of thing when the information is important, as otherwise it will not be available to screenreaders and a11y users.

Note: :after should be replaced with ::after . While both work, it’s technically not a pseudo-class but a pseudo-element which use a double colon.

You can’t. CSS is a presentation language. It isn’t designed to add content (except for the very trivial with :before and :after ).

Quentin is correct, it can’t be done with CSS. If you want to add a title attribute, you can do it with JavaScript. Here’s an example using jQuery:

Yes i did but this was done in my base page where some other page can be included i dont know why its not working

can you post a link? hard to say without seeing it. try enclosing the above with $(document).ready(function() < and >); so that the jquery waits until the document (and thus target element) has loaded before running.

As Quentin and other suggested this cannot totally be done with css(partially done with content attribute of css). Instead you should use javascript/jQuery to achieve this,

document.getElementsByClassName("mandatory")[0].title = "mandatory"; 
$('.mandatory').attr('title','mandatory'); 
document.getElementsByClassName('mandatory')[0].setAttribute('title', 'mandatory'); $('.jmandatory').attr('title', 'jmandatory');
 Place the Mouse Over the following elements to see the title, 



It is possible to imitate this with HTML & CSS

If you really really want dynamically applied tooltips to work, this (not so performance and architecture friendly) solution can allow you to use browser rendered tooltips without resorting to JS. I can imagine situations where this would be better than JS.

Читайте также:  Simple Multiple Choice Quiz with JavaScript

If you have a fixed subset of title attribute values, then you can generate additional elements server-side and let the browser read title from another element positioned above the original one using CSS.

div < position: relative; >div > span < display: none; >.pick-tooltip-1 > .tooltip-1, .pick-tooltip-2 > .tooltip-2
 
Hover to see first tooltip
Hover to see second tooltip

Note: It’s not recommended for large scale applications because of unnecessary HTML, possible content repetitions and the fact that your extra elements for tooltip would steal mouse events (text selection, etc)

Источник

Атрибут title

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

Синтаксис

Значения

Любая текстовая строка. Строка должна заключаться в двойные или одинарные кавычки.

Значение по умолчанию

      
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

documenting div sections, use title attribute?

I’m looking for the most terse way to document sections of my page, e.g. div sections. Anything wrong with using the title attribute, e.g.

? P.S. In case relevant, I’m using the IntelliJ IDE, but new to its various capabilities, e.g. automatic formatting control and other ways to be able to easily understand sections of my pages.

If an element has a title attribute, most browsers show a tooltip with the attribute’s value when you hover over it. In this case, they’ll show a “Payment Area” tooltip when you hover anywhere over that div . So, it might not be appropriate.

Years late here, but if it’s a comment, use a comment. Also, any worthwhile web framework allows for composing views from partials, so make a high level skeleton and name your partials well and more than half of the problem you’re having here will solve itself.

5 Answers 5

If an element has a title attribute, most browsers show a tooltip with the attribute’s value when you hover over it. In this case, they’ll show a “Payment Area” tooltip when you hover anywhere over that div .

HTML attributes, in general, have a purpose. HTML has comments for documentation! Try them:

You mentioned that you didn’t want the overhead of comments. If you count up the characters (including the required space before the attribute, they’re actually the same length:

(But, I agree, they do look bigger!)

🙂 Yah, I wanted to avoid the extra line and find something that describes the div (section) itself — on same line.

I think I’m going to go with using the id, giving it a special naming convention if this element has no special style or javascript associated with it, e.g. Then, if it has javascript or css associated with it, I’ll change it to . perhaps I should do >

Читайте также:  Center an Image using text align center

@Ray I agree that comments do feel a little bigger than attributes, but they work just as well on the same line (see edit). If you would rather use an attribute, why not give each element a normal id (like paymentArea ), regardless of whether that id is used by CSS or JavaScript?

Thanks Sidnicious, I guess with the id they are a little smaller. I think one hold back I’ve had is using various editor formatters and having them move stuff around in ways I don’t like. But outside that, I think Jason’s answer and associated comments are good.

Alternate idea: Use PHP comments instead of HTML comments — if it has no bearing on how the web page will be affected, users don’t need to see it in the source.

I would probably use id s, that way you can also use them as hooks for your CSS and JavaScript.

Otherwise, Gabe’s Answer makes a good case for data attributes. John Resig explains why they are good here: http://ejohn.org/blog/html-5-data-attributes/

I don’t think I want to imply I’m using this information for anything, other than documenting what a section is for. If I am applying a style or using javascript, then I would use a more condensed description, without spaces, etc. Some of my descriptions are longer.

Let’s say I have 4 divs (sections) that use the same class styling, and other than that do nothing special. To me if I use the id attribute, with a more variable like name, I’m implying functionality / complexity. I don’t want to do that. I’d use a comment to document, but this way seems more succinct to me.

Ok. But if you give them an id with a functional name, like id=»payment_area» , then 1. you have documented the div and 2. made your code future friendly in case you want to add functionality or specific styles.

I see what you’re saying, but this then makes me wonder if there is a style for payment_area somewhere, or perhaps it’s being used by javascript. I’m an css/html «newbie», but doesn’t sectioning things like this also imply additional complexity? Perhaps I could use one or the other depending on whether there really is additional «id-specific» functionality for this div?

I would recommend using the HTML5 custom attributes standard:

Basically, precede the name with data- and the browser will ignore it.

Well, if you don’t want to use the id attribute, then it’s just the standard I follow, since HTML5 is showing up more and more. Just trying to follow recommended practices.

The title attribute isn’t meant for divs — I haven’t checked the official specs, but I don’t think it’s even a supported attribute. The better practice is to use the «id» attribute. This has the added benefit of providing hooks for your CSS.

You can also take it a step further and use html5, which provides you with more descriptive elements such as , , and

Читайте также:  Php write session cookie

Edit: as per comment by steveax, the title attribute isn’t invalid. I think the gist of my answer remains valid, though.

I don’t think I want to imply I’m using this information for anything, other than documenting what a section is for. Do you know how the aforementioned html5 elements degrade in browsers (or browser versions) not yet supporting html5?

I personally find the ID useful for my own organization — the css is an added benefit. As for html5, you can make IE handle them easily — in the of your page, using conditional comments, simply use javascript to create the appropriate element — you don’t even need to insert it into the DOM. Then you can style it as if it were a , or anything.

Title attribute is fine on a div , but it’s for users not authors. Misusing @title for author documentation is a bad practice. Why not just use comments?

Thanks steveax. Yah, I don’t want the user to see tooltips. I wanted something more succinct than comments — e.g. not a separate line, not extra < >. It looks like perhaps my solution is to use something like

, as long as older non-html5 browsers don’t get bothered, which I don’t know ??

Источник

Всплывающие подсказки title на CSS

Рассмотрим возможность создания простых всплываек при наведении мыши на картинку или какой-нибудь html блок. При этом во всплывайки мы сможем добавлять только текст (ссылки и теги не вставить).

Как известно, html имеет «всплывайки-подсказки» по умолчанию — это title. Его можно вставить на любой тег, ссылку или кнопку:

Читать

. Но у title есть существенный минус — он задан со стандартным оформлением, изменить который можно только с помощью скриптов. И второе, — title имеет задержку перед появлением.

Это бывает крайне не удобно, когда пользователь наводит на что-то мышь и ему приходится ждать появление подсказки. Часто он просто не догадывается о том, что там должно что-то появиться, быстро отводит мышь и подсказка вовсе не появляется.

Воспользуемся псевдоэлементом after , чтобы создать моментальные подсказки по аналогии с title, которые лишены этих недостатков. Сначала добавим сами элементы:

Обратите внимание — вместо title я использую выдуманный атрибут data-text , в нем и будет содержаться текст наших подсказок.

Теперь добавим css стиль, который заставит магическим образом красиво появляться подсказкам над картинками и обычным текстом в данном случае:

Здесь при наведении на .item «создается» псевдоблок after, в котором в качестве контента берется значение атрибута data-text. С помощью position: absolute; и z-index: 1; мы позиционируем подсказку сверху картинок.

Сейчас подсказка показывается снизу картинки. Чтобы она была строго посередине, измените класс так: .item

.item:hover::after content: attr(data-text);
position: absolute;
left: 50%;
width: 160px;
margin-left: -90px;
top: 50%;
margin-top: -30px;
height: 40px;
z-index: 1;
background: rgba(222, 222, 222, 0.82);
font-family: Arial;
font-size: 14px;
padding: 10px 10px;
color: #000;
>

Таким образом, достаточно просто сделать эффектные подсказки по аналогии с title не прибегая к использованию скриптов.

Источник

Оцените статью