Давайте обратим свои взоры к теме сокращений на веб-страницах, а точнее понятности этих сокращений читателям. В данной статье рассматриваются теги abbr и acronym и нюансы, связанные с ними.
Внимание. В спецификации HTML5 элемент acronym объявлен полностью устаревшим и его настоятельно рекомендуют исключить из употребления. Взамен предлагается использовать элемент abbr (уточнения от 10.11.2011).
Разбираемся с терминалогией
Аббревиатуры и акронимы должны быть понятны всем и всегда
HTML теги и
HTML 4 предоставляет нам два элемента логического форматирования, используемых для выделения аббревиатур и акронимов — abbr и acronym , соответственно. У данных тегов есть атрибут title в котором дается разъяснение термина. Любой нормальный браузер при наведении курсора мыши на такой термин отобразит всплывающую подсказку, заданную атрибутом title .
Билли, который не любит W3C
В списке знакомых ему элементов указан лишь элемент ACRONYM . Но я уверен, что это будет исправлено в седьмой версии браузера.
Конечно, можно махнуть на это рукой и использовать вместо тега abbr тег acronym , но тогда не удивляйтесь если голосовой агент пользователя будет произносить буквенную аббревиатуру УРИ не побуквенно, а одним словом, и получится имя Ури из Х/Ф «Приключения электроника» . Но можно найти и обходной путь, например, вставить внутрь ABBR элемент SPAN :
И лучше этот процесс автоматизировать, выполняя вставки с помощью скрипта, после загрузки документа и только для IE. И что очень важно, не нужно будет менять правильный исходный текст документа.
Наводим CSS-марафет
Так как abbr и acronym элементы логического форматирования, то браузеры могут по разному отображать их на странице. Например, Mozilla Firefox и Opera отображают данные элементы с черным подчеркиванием в виде точек, Konqueror — выделяет курсивом, а IE никак визуально не выделяет ( acronym ).
Поэтому не помешает задать стили, которые бы унифицировали отображение данных элементов в разных обозревателях.
Учебник HTML5
» Всё о HTML5 на русском
Тег в HTML5
Использование этого тега показано на следующем примере:
p > В abbr title =»Hyper Text Markup Language 5″ > HTML5 abbr > есть новый тег abbr. p >
Необязательный атрибут title указывает текст всплывающей подсказки. Если он отсутствует то подсказка не будет отображаться, но слово будет выделено подчеркиванием.
Кстати по умолчанию подчеркивание отображается только в браузерах Mozilla FireFox и Opera. Для остальных браузеров необходимо вручную прописать:
Что касается старых версий Internet Explorer, то для них необходимо прописать следующий скрипт:
HTML тег abbr
Тег определяет, что последовательность символов является аббревиатурой.
Аббревиатура и акроним оба являются сокращением некоего сочетания слов. И аббревиатура и акроним представляются набором букв.
Универсальный атрибут title может использоваться в теге , чтобы предоставить расшифровку аббревиатуры при наведении на нее указателя мыши.
Текст внутри тега никак не выделяется браузерами, кроме Opera до версии 15, которая добавляет к тексту пунктирное подчёркивание.
Abbr HTML Tag: Here’s When To Use It With Abbreviations
Sharing is caring!
Code Example
Abbreviations and Acronyms
Whenever the tag is used, you should always use the title attribute, which indicates the meaning of the abbreviation or acronym.
Deprecated tag
Older HTML specifications included a separate element. This has now been deprecated in HTML5, and acronyms should be marked up with the element instead.
The element
If you are using an unfamiliar or unusual abbreviation, you may want to consider also including a element so provide additional information about the word or phrase.
в HTML
Тег предназначен для выделения аббревиатур и сокращений в тексте. При помощи атрибута title можно добавить расшифровку сокращения. В некоторых браузерах текст, заключенный в элемент с атрибутом title , по умолчанию подчеркивается пунктирной линией. Если же атрибута нет, то текст никак не выделяется.
Атрибуты
Личные атрибуты: нет.
accesskey — устанавливает клавишу быстрого доступа для фокусировки на элементе.
class — задает имя класса или классов HTML-тега, используемых в CSS (Каскадные таблицы стилей).
dir — указывает направление текста внутри элемента.
id — задает имя идентификатора тега, который может использоваться в качестве «якоря» или в таблицах стилей.
lang — указывает язык, на котором написан текст внутри HTML-элемента.
style — необходим для применения встроенных стилей CSS к тегу.
tabindex — устанавливает порядок табуляции между элементами (клавиша Tab ).
title — выводит всплывающую подсказку при наведении курсора мыши на HTML-элемент.
Тип тега
Модель тега: inline (встроенный, уровня строки).
Может содержать: inline-теги, обычный текст и спецсимволы HTML (мнемоники).
Internet Explorer 6.0 не понимает тег , вместо него можно использовать .
в HTML
По умолчанию, текст заключенный в контейнере подчеркивается пунктирной линией.
Синтаксис
Атрибуты
Также для этого тега доступны универсальные атрибуты и события.
Закрывающий тег
Пример. Добавление аббревиатуры на веб-страницу
Примечание
Браузер Internet Explorer до 6 версии включительно не поддерживает тег , взамен рекомендуется использовать тег .
Спецификация ?
Спецификация
Статус
WHATWG HTML Living Standard
Живой стандарт
HTML5
Возможная рекомендация
HTML 4.01 Specification
Рекомендация
Спецификация
Каждая спецификация проходит несколько стадий одобрения.
Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
Cand >Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
Draft ( Черновик спецификации ) — первая черновая версия стандарта.
Особняком стоит живой стандарт HTML ( Living ) — он не придерживается традиционной нумерации версий, поскольку находится в постоянной разработке и обновляется регулярно.
Браузеры: Настольные Мобильные ?
Internet Explorer
Chrome
Opera
Safari
Firefox
7
2
1.3
1
1
Android
Firefox Mobile
Opera Mobile
Safari Mobile
1
1
6
1
Браузеры
В таблице браузеров применяются следующие обозначения.
— элемент полностью поддерживается браузером;
— элемент браузером не воспринимается и игнорируется;
— при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.
Число указывает версию браузреа, начиная с которой элемент поддерживается.
в HTML
Во! Отлично! Спасибо! Теперь осталось настроить Типинатор на хоткеи и, главное, запомнить, какой соответствует какому тегу. Очень, очень полезная инфа — аффтару зачот.
Спасибо за урок HTML-грамотности хотя многие теги редко используются, но в свете данной статьи заставляет взглянуть на них по новому
Allpa, Сергей, спасибо за хорошие отзывы. Я только что заметил, что вопрос о тегах ABBR и ACRONYM освещен не полностью. Вскоре напишу дополнение.
и насколько такие теги значимы для поисковиков? на что влияют?
oyurkov, точных цифр ты нигде не найдешь. Достоверно, что атрибут title в тегах abbr и acronym прекрасно учитывается поисковыми машинами. Вообще, конструкция внутри соответствующего тега логической разметки имеет больший вес, чем просто воткнутая непонятно где в теле страницы.
Хотя в данной области все больше строится на предположениях и здравом смысле. И еще на допущении, что в Гугле и Яндексе работают далеко не идиоты. Уж точно не глупее большинства доморощенных сео-турбо-манимейкеров :).
Весьма интересная статейка, только применимо ли это к вордпресс? Там то для поисковой оптимизации насколько я знаю применяются другие приемы?
Тег abbr в языке разметки html представляет собой аббревиатуру, сокращение слов. Этот тег имеет закрывающий дескриптор.
Уроки HTML
Тег abbr-Аббревиатура
Урок 5
Выглядит как слово, подчеркнутое пунктирной линией. Важным атрибутом тега abbr является тег title, который пишется в первом теге после слова abbr .
При наведении на слово, отмеченное тегом abbr, возникает всплывающая подсказка, поясняющая смысл аббревиатуры.
HTML Tag
Syntax
Examples
Basic tag usage
With Title Attribute
Plural
If an abbreviation or acronym is pluralized, the value of any title attribute must match any pluralization of the contents.
Here’s an example of the plural being outside the element:
Here’s an example of the plural being inside the element:
Attributes
Attributes can be added to an HTML element to provide more information about how the element should appear or behave.
There are 3 kinds of attributes that you can add to your HTML tags: Element-specific, global, and event handler content attributes.
Element-Specific Attributes
This table shows the attributes that are specific to the tag/element.
Attribute
Description
None
Global Attributes
The following attributes are standard across all HTML5 elements. Therefore, you can use these attributes with the tag , as well as with all other HTML tags.
accesskey
class
contenteditable
contextmenu
dir
draggable
dropzone
hidden
id
inert
itemid
itemprop
itemref
itemscope
itemtype
lang
spellcheck
style
tabindex
title
translate
For a full explanation of these attributes, see HTML 5 global attributes.
Event Handler Content Attributes
Event handler content attributes enable you to invoke a script from within your HTML. The script is invoked when a certain «event» occurs. Each event handler content attribute deals with a different event.
Below are the standard HTML5 event handler content attributes.
Again, you can use any of these with the element, as well as any other HTML5 element.
onabort
oncancel
onblur
oncanplay
oncanplaythrough
onchange
onclick
oncontextmenu
ondblclick
ondrag
ondragend
ondragenter
ondragexit
ondragleave
ondragover
ondragstart
ondrop
ondurationchange
onemptied
onended
onerror
onfocus
onformchange
onforminput
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadstart
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onmousewheel
onpause
onplay
onplaying
onprogress
onratechange
onreadystatechange
onscroll
onseeked
onseeking
onselect
onshow
onstalled
onsubmit
onsuspend
ontimeupdate
onvolumechange
onwaiting
For a full explanation of these attributes, see HTML 5 event handler content attributes.
Differences Between HTML 4 & HTML 5
To see more detail on the two versions see HTML5 Tag and HTML4 Tag. Also check out the links to the official specifications below.
Template
For more information on attributes for this tag, see HTML5 Tag and HTML4 Tag.
HTML5 Doctor
Helping you implement HTML5 today
The abbr element
What the spec says
The abbr element represents an abbreviation or acronym…
Straightforward enough, right?
How to use it
Keep in mind that abbreviations aren’t always a series of uppercase letters. You can also use to mark up a shortened word. For example:
The title attribute creates a tooltip for the user when they hover their cursor over the element:
Tooltip displayed to the user when hovering over an element
The dotted border/underline is shown by default in Firefox and Opera, but IE8, Safari, and Chrome need a line of CSS:
When to use title
Also, if you include the title attribute on the first use of an abbreviation, it’s generally accepted practice to omit it on subsequent uses.
Acronyms and abbreviations: what’s the difference?
Although very similar, there is a slight difference between an acronym and an abbreviation. An acronym is a set of letters that forms a new word, such as NATO , while an abbreviation, such as BBC , does not, since you say each letter separately.
So why one over the other?
There’s always been a lot of confusion over these two elements and their usage. Witness it in this archive letter from 1997.
Conclusion
Category
Tom Leadbetter
This article was written by Tom Leadbetter . Tom is a designer/frontend web developer based in Liverpool, UK. He is football (soccer) mad, loves gaming and other geeky bits n bobs. Stalk him on Twitter.
29 Responses on the article “The abbr element”
For love of markup, please read my article on abbreviations, citations and definitions. I‘ve been fighting against this nonsense use of abbr to define initialisms. http://camendesign.com/abbr_redux
It is, then, disingenuous to leave a comment such as the one above that reads with such authoritarianism and condescension.
Of course, I say that in the scope that everyone is entitled to their opinion, and are as free to express it in any way they see fit as I am. I just can’t help but feel that your arguments and supporting assertions are less credible due to your less than tactful delivery.
Okay, let me say it like this. Who does this article actually help? I tried for several years marking up every acronym / initialism with its full description, and all it did was create a massive amount of anal-retentive work that didn’t serve any solid purpose. If you actually followed the advice of this article, you would eventually go mad. It’s writing, for writing’s sake, rather than trying to nail down a practical, meaningful, semantic reasoning for using abbreviations and definitions (which are not even mentioned here!!).
Sorry, HTML5Doctor, but you should already know that I speak my mind freely and only mean the best out of it, but this article helps nobody and teaches 10 year old practices that are and continue to be worthless to web authors and users. I’m pointing you to my article because _I gave a damn_ and thought through the semantics and practical value of this markup rather than regurgitating the spec.
Hi Kroc. Thanks for linking to your article, some good points there. I particularly like your examples of “!-” and “TCO”.
Let’s get some semantics straight, shall we? There is no difference between an acronym and an abbreviation other than an acronym is a specific kind of abbreviation: one that forms a word with the initial letters of other words, as stated in the article. BBC is a specific form of abbreviation called initialism: an abbreviation consisting of initial letters pronounced separately.
NATO and BBC (both examples from the article) are both technically abbreviations, so the tag is semantically sound by its official definition.
I’m a screen reader user. Screen reader are able to define a different behaviour for each element , acronym and abbr, seperatley.
I personally, as a lot of other blind users, let the screen reader read the expanded text for and let the screen reader read the acronym for .
I think you get the point, both groups are read differently. You would read always the expanded version of the first group, and you would always read the acronym of the second group.
Screen readers are able to “smart read” the second group, NATO as a word and BBC spelled. The only thing the screen reader doesn’t know, when to read the expanded vesion and when to read the acronym.
Therefore the differentiation in HTML4 was very important and the screen reader offered the possibility to distinguish the behaviour between gropu 1 (abbr) and group 2 (acronym).
The grammar nazi in me wanted to share something.
There are initialism, acronyms and abbreviations – all do essentially the same thing (reduce a long word, or collection of words into a shorter word), but the definitions of each are slightly different.
An initialism is where a group of words are reduced to the first letter (or in some cases, first few letters), and those letters are placed one beside the other, in the same order as the words initially occured. So “BBC”, “CNN”, “FBI” are initialisms.
An acronym is similar to an initialisation, however, the resulting string of characters is able to be pronounced to produce a new word. “SCUBA”, “NASDAQ” and “FUBAR” are acronyms.
An abbreviation is where some characters from a word are removed, to produce a condensed form still recognisable as meaning the same as the original word. So “Dr” (Doctor), “Mr” (Mister), “Mrs” (Missus), “etc” (Etcetera) are abbreviations.
One reason to do away with the acronym element is that, as Cameron pointed out, an acronym is a special kind of abbreviation. Abbreviation is a more generic name, and HTML tends to favor generic elements with its limited semantics. (Also, it happens that the English “acronym” is not the same thing as the French “acronym” and perhaps some other European derivatives.)
Kroc Camen’s article was a great read (even though the comment’s tone and the very start of the linked article didn’t make a good impression). I like the invitation to not drown our text in semantic elements such as abbr just for the sake of it (bloat), and when we don’t really understand what that element means (risk of errors) or how it’s used by user agents.
I would say the weakest point with this article and Kroc Camen’s article is that there is very little focus (or research) on User Agent implementations. Kroc advises to use abbr with no title attribute to tell user agents (especially screen readers) that the text should be read as a word and not as separate letters, and to use abbr plus the title attribute to give the spoken form of some abbreviations. That second use case seems sensible regardless of the efficiency of implementations (or lack thereof). The first one, on the other hand, is not really supported by HTML4 and HTML5 specification text, and only makes sense if user agent implementations are consistent with this advice. Also, what about CSS 2.1 aural styles, do they help?
@Kroc — “`HTML` is a definition not an abbreviation.” — this is not true. “The dfn element represents the defining instance of a term.” HTML is by definition an abbreviation (rimshot! sorry :), although you could choose to mark up the first instance with in addition to .
For being able to specify if a word is to be read (normal/spell-out) you can use AAural CSS: http://www.w3.org/TR/CSS2/aural.html At the moment there aren’t a lot of screen readers making use of this CSS property but this would be the right semantic way to do it.
IMHO leaving out the title attribute isn’t the right way to deal with different kind of pronounciation.
ABBR and ACRONYM were supported in IE when using JAWS. You probably didn’t see any tool-tip but you were able to distinguish between reading the expanded or non-expanded word.
I don’t find any semantic way to provide this reading differentiation semantically in HTML5 without making any WAI-ARIA gymnastics.
While I agree with Kroc that this article could be extended with more information, I don’t agree with it being a useless post. At the very least, I now know WHY abbr is prefered over acronym, in the specification, anyway.
I also agree that there should be more research in what UA actualy DO with both tags. I think I might give a shot at that once i sorted my own site out.