htmlbook.ru — Как правильно писать заголовок страницы

title

The title global attribute contains text representing advisory information related to the element it belongs to.

Try it

The main use of the title attribute is to label elements for assistive technology.

The title attribute may also be used to label controls in data tables.

While title can be used to provide a programmatically associated label for an element, this is not good practice. Use a instead.

Multiline titles

The title attribute may contain several lines. Each U+000A LINE FEED ( LF ) character represents a line break. Some caution must be taken, as this means the following renders across two lines:

HTML

p> Newlines in code>titlecode> should be taken into account. This span title="This is a multiline title"> example span span> has a title a attribute with a newline. p> hr /> pre id="output">pre> 

JavaScript

We can query the title attribute and display it in the empty element as follows:

const span = document.querySelector("span"); const output = document.querySelector("#output"); output.textContent = span.title; 

Result

Title attribute inheritance

If an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on.

If this attribute is set to the empty string, it means its ancestors’ title s are irrelevant and shouldn’t be used in the tooltip for this element.

HTML

div title="CoolTip"> p>Hovering here will show "CoolTip".p> p title="">Hovering here will show nothing.p> div> 

Result

Accessibility concerns

Use of the title attribute is highly problematic for:

  • People using touch-only devices
  • People navigating with keyboards
  • People navigating with assistive technology such as screen readers or magnifiers
  • People experiencing fine motor control impairment
  • People with cognitive concerns

This is due to inconsistent browser support, compounded by the additional assistive technology parsing of the browser-rendered page. If a tooltip effect is desired, it is better to use a more accessible technique that can be accessed with the above browsing methods.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 13, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Html add page title

Определяет заголовок документа. Элемент не является частью документа и не показывается напрямую на веб-странице. В операционной системе Windows текст заголовка отображается в левом верхнем углу окна браузера (рис. 1). Допускается использовать только один тег на документ и размещать его в контейнере .

Рис. 1. Вид заголовка в браузере Internet Explorer

Рис. 1. Вид заголовка в браузере Firefox

Синтаксис

Закрывающий тег

Атрибуты

     

.

Примечание

Тег выполняет множество задач, как прямо, так и косвенно. Ниже описано какую роль выполняет заголовок страницы.

  • По тексту заголовка пользователь получает дополнительную информацию, что это за сайт, на котором он находится и как называется текущая страница. Не стоит думать, что достаточно в документе указать логотип сайта и проигнорировать заголовок, ведь посетитель может свернуть окно. В свернутом виде заголовок также отображается на кнопках панели задач, поэтому можно легко ориентироваться, с каким сайтом в данный момент работать, а не перелистывать их по очереди.
  • Большинство браузеров поддерживают возможность сохранения веб-страницы на локальный компьютер. В этом случае имя сохраненного файла совпадает с названием заголовка документа. Если в тексте заголовка содержатся символы недопустимые в имени файла (\ / : * ? » < >|), они будут проигнорированы или автоматически заменены другими дозволенными символами.
  • При сохранении в разделе браузера «Избранное», адрес текущей страницы с ее заголовком помещается в список предпочитаемых ссылок. Поскольку этот список, как правило, хранится в виде отдельных файлов, к их именам также прилагается уже вышеописанное правило.
  • В результатах поиска по ключевым словам, поисковые системы используют заголовок страницы для указания ссылки на данный документ. Интересно написанный заголовок, содержащий ключевые слова, привлечет больше внимания посетителей и увеличит шансы на то, что сайт посетит больше людей.

Статьи по теме

Источник

HTML Tag

The tag defines a title of an HTML document. A title tag must be the precise description of a page’s content. The title is displayed in the browser toolbar and on search engine results pages (SERPs) as a clickable headline.

The content of the title is an important component that search engine algorithms use to determine the order of list pages’ appearance in search results.

An optimized title tag increases the rank on SERPs and the click-through rate.

  • the short title and description of a page which is displayed at the top of the browser window,
  • the ranking of search engines,
  • the default name for bookmarks created by the user,
  • the link headline when it is shared on social media,
  • the clickable headline.

There should be only one element in an HTML document located inside the section.

Here are some tips to create good titles:

  • Avoid the use of titles with one or two words. Instead, you can use a descriptive phrase.
  • If possible, avoid special characters as they can be displayed by browsers differently.
  • In general, search engines display about 55-60 characters of a title. When using a longer title, ensure that the important parts are at the beginning.
  • Avoid the use of a list of words as a title.
  • Ensure that the title is unique in your site.

Syntax

The ) tags.

Example of the HTML tag:

html> html> head> title>W3Docs - learn HTML, CSS, PHP, JavaScript online. title> head> body> p>The main content of the page. p> body> html>

Источник

: элемент заголовка документа

HTML-элемент заголовка ( ) определяет заголовок документа, который отображается в заголовке окна браузера или на вкладке страницы. Он содержит только текст, а теги внутри элемента игнорируются.

Категории контента Метаданные.
Допустимое содержимое Текст, который не является межэлементным разделителем.
Пропуск тегов Открывающий и закрывающий теги обязательны. Обратите внимание, что отсутствие заставляет браузер игнорировать остальную часть страницы.
Допустимые родители Элемент , который не содержит других элементов .
Допустимые ARIA-роли Нет
DOM-интерфейс HTMLTitleElement (en-US)

Атрибуты

К этому элементу применимы только глобальные атрибуты.

Примечание

Элемент всегда используется внутри блока .

Заголовок страницы и SEO

Содержимое заголовка страницы может иметь важное значение для поисковой оптимизации (SEO). Как правило, более длинный описательный заголовок будет лучше ранжироваться (Ranking), чем короткий или скучный. Не только содержимое заголовка является одним из компонентов, используемых алгоритмами для определения порядка, в котором перечисляются страницы в поисковой выдаче, но и сам заголовок является приёмом, которым вы привлекаете внимание читателей бегло просматривающих результаты поиска.

Несколько методических рекомендаций и советов для составления хороших заголовков:

  • избегайте заголовков состоящих из одного или двух слов. Используйте описательные фразы или сочетание термин-определение для страниц глоссария (словарь терминов) или справки;
  • поисковые системы, как правило, отображают примерно 55-60 первых символов заголовка страницы. Текст, превышающий это количество символов, может быть потерян, так что постарайтесь, чтобы заголовки не были длиннее. Если вам нужно использовать более длинный заголовок, убедитесь, что важные части появляются раньше и что нет ничего критического в части заголовка, которая может быть отброшена;
  • избегайте специальных символов, когда это возможно; не все браузеры будут отображать их одинаково. Например, »
  • не используйте ключевые слова («keyword blobs»). Если ваш заголовок состоит только из списка слов, то алгоритмы будут часто искусственно понижать позицию вашей страницы в поисковой выдаче;
  • убедитесь, что ваш заголовок является уникальным на вашем сайте, насколько это возможно. Повторяющиеся или частично повторяющиеся заголовки могут способствовать неточным результатам поиска.

Пример

title>Потрясающий заголовок страницыtitle> 

Этот пример устанавливает заголовок страницы (отображается в верхней части окна или вкладки браузера) как «Потрясающий заголовок страницы».

Проблемы доступности

Важно указать такое значение title , которое описывает назначение страницы.

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

Пример

title>Меню - Китайская еда Синий дом - FoodYum: онлайн на вынос сегодня!title> 

Для того чтобы помочь пользователю, обновите значение title , чтобы отразить важные изменения состояния страницы (например, проблемы с проверкой формы).

Пример

title>2 ошибки - ваш заказ - Китайская еда Синий дом - FoodYum: онлайн на вынос сегодня!title> 

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on 4 мар. 2023 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

A Step-by-Step Gide to Setting a Title in HTML

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, volunteer authors worked to edit and improve it over time.

The wikiHow Tech Team also followed the article’s instructions and verified that they work.

This article has been viewed 59,876 times.

Every web page needs a title. Why doesn’t yours? One of the major tag pairs in HTML is the tags; the title tag affects several functions of websites, from the default bookmark titles through to flashing words drawing your attention back to the site, even when in a different tab.

  • Create your HTML in a program like Atom, Brackets, TextEdit, or Notepad++.
  • Add the Title Tag to your code.
  • Change «Something» to the title you want and save the file.

Creating the HTML Layout

Image titled Title tag html

Create the body. Using the tags, create a .html file with either tag on a new line. Make sure to close the tag with .

Image titled Title tag head

Add the section. Placing the tags in between the tags, define the head (metadata section) section. Make sure to close the tag with .

Image titled Title tag content

  • Optionally, add some ‘test’ code in the body (or content) section to make sure that you’ve coded it correctly. If the content shows, it means that the code is parsing (loading). If not, it means that you may have made a typo or some other thing that is not letting it load.

Adding the Title Tag

Image titled Title tag title content

  • Make sure to close the tag with . These two tags can be on the same line. In between the starting and closing title tags, write what you want your title to say.

Testing the Code

Image titled Title tag save

Save your file to an easily accessible location. Name your file as something.html , replacing something with what you wish. Remember that the index.html file is the ‘home’ or ‘landing’ page of your website.

Image titled Title tag open

Open your page in your preferred browser. Browsers like Google Chrome, or Mozilla Firefox are good for front-end website development. Go ahead and open your .html file. You can use short keys like ⌘ Cmd + O or Ctrl + O to open the file in most browsers.

Image titled Title tag view

Look at the top of the tab for your title. If your desired title shows, the code has loaded and worked! If not, and it shows your filename instead (something.html), you may have made a mistake; check your code for typos then try again.

Community Q&A

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Источник

Читайте также:  Javascript чему равен null
Оцените статью