Sub topic 4
Writing a good title
This chapter assumes you can write basic HTML elements and attributes, and that you know a document has a doctype, an html element, a head, and a body. It also assumes you know in general what a browser and a search engine do with a page. Here you will learn what the title element does, who reads it, how to write a useful one, and which mistakes to avoid.
What the title element is
The title element gives the document its name. It lives in the head, and its content is plain text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Trail Running Shoes - Example Store</title>
</head>
<body>
<h1>Trail Running Shoes</h1>
</body>
</html>The title does not appear in the page itself. Browsers and other software show it somewhere else. Each of these tools reads it:
- Browser tabs and window title bars
- Browser history, bookmarks, and the "recently closed" list
- Search engine results, where it is usually the clickable headline
- Screen readers, which typically announce it when a page loads
- Link-sharing tools, which may use it when no other preview title exists
The title element is the only metadata item that the HTML specification requires in nearly every document. A page without a title fails validation. The exception is a document whose title comes from a higher-level protocol, such as the subject line of an HTML email.
Because so many tools read it in different places, a title must make sense without the page around it. A bookmark list shows only titles. A search result shows the title and a short snippet.
How the browser reads the title
Rules for the element
The specification sets a few rules:
- A document may have only one
titleelement in itshead. - The element may contain only text. Child elements are not allowed.
- The text must not be empty for the document to be useful. An empty
titleis valid syntax but gives the user nothing.
Text, not markup
The parser treats the content of title as text with character references. It decodes references such as &, but it does not build elements from tags. If you write a tag inside a title, the tag appears literally.
<title>Fish & Chips <em>Menu</em></title>The tab shows Fish & Chips <em>Menu</em>, including the angle brackets. Write & for an ampersand and < for a less-than sign. A bare & often works because browsers recover from it, but it is invalid in some cases and a validator may report it. Use the reference.
Whitespace
Browsers collapse runs of whitespace and trim the ends when they read the title. These two titles produce the same result:
<title>Order history</title>
<title>
Order history
</title>Collapsing makes multi-line titles harmless in the browser. Keep titles on one line anyway so source diffs and templates stay readable.
Reading and changing the title with JavaScript
document.title returns the processed text, with whitespace stripped and collapsed. Assigning to it changes the tab text immediately.
console.log(document.title);
document.title = "Cart (2 items) - Example Store";
console.log(document.title);If a document has several title elements, document.title reads the first one in tree order. Do not rely on that. Keep exactly one.
SVG has its own title element for describing graphics. A title inside an inline svg in an HTML page is a different element and does not set the document title. Put the document title in the head.
Writing a useful title
Say what this page is
A good title names the specific page, so someone who sees it alone can tell it from other pages on the same site. Compare these:
| Weak title | Problem | Better title |
|---|---|---|
| Home | Says nothing about the site | Example Store - Running Shoes and Gear |
| Untitled Document | Editor default left in place | Trail Running Shoes - Example Store |
| Example Store | Same text on every page | Returns Policy - Example Store |
| Shoes, shoes, cheap shoes, buy shoes online, best shoes | Keyword stuffing | Lightweight Trail Running Shoes - Example Store |
| Page 2 | Depends on context the reader lacks | Trail Running Shoes, Page 2 - Example Store |
Put the specific part first
Tabs are narrow. When many tabs are open, the browser shows only the first few characters. Search results also cut long titles. Put the words that identify the page first and the site name last, separated by a hyphen, a pipe, or a similar mark.
<title>Returns Policy - Example Store</title>The home page is an exception. There the site name usually comes first or stands alone, because the site is the subject.
Keep it short enough
No rule sets a maximum length. Search engines truncate by rendered pixel width, not by character count, so a limit would be approximate anyway. A title of roughly 50 to 60 characters usually displays in full on desktop search results. Longer titles are valid, but the end may be cut off in results and tabs. The important words belong near the start.
Short does not mean vague. "Shoes" is short but tells the reader little.
Make each title unique
Two pages with the same title are hard to tell apart in a tab bar, a history list, or search results. Generate titles from page data so that each page gets its own. A product page uses the product name. An article page uses the article headline.
Match the visible heading, but do not copy it blindly
The title and the page's h1 serve different purposes. The h1 heads the content on the page. The title names the page outside the page. They should agree on the subject, yet they do not have to match word for word. An h1 of "Trail Running Shoes" pairs well with a title of "Trail Running Shoes - Example Store". The brand suffix belongs in the title because the reader sees it away from the page.
Avoid common errors
- Keyword stuffing. A string of repeated search terms reads badly and gains nothing. Search engines may ignore it or replace it.
- Reusing one template string everywhere. A site-wide
<title>Example Store</title>in a shared layout is the most common cause of duplicate titles. - Leaving editor defaults. "Document", "Untitled", and "New Page" often ship to production.
- Putting markup in the title. Tags display as text.
- Using the title for instructions or marketing slogans. A tab bar is a poor place for "Click here for the best deals!"
- Forgetting to update it in a single-page app. The first page loads and sets a title, then route changes leave it unchanged.
Search engines are free to rewrite your title in results. They may do this when the title is missing, too long, stuffed with keywords, or poorly matched to the query. A clear, accurate title lowers the chance of a rewrite, but nothing guarantees one will not occur.
Accessibility
The Web Content Accessibility Guidelines include a Level A success criterion called Page Titled (2.4.2). It requires that pages have titles that describe their topic or purpose. Screen reader users often rely on the title to learn where they are after a navigation, and to tell several open windows apart.
The same applies to dynamic pages. In a single-page application, the browser does not load a new document when the route changes, so it does not announce a new title. You must update the title yourself, and you should also move focus or use a live region so assistive technology notices the change.
const SITE_NAME = "Example Store";
function setPageTitle(pageName) {
document.title = pageName ? `${pageName} - ${SITE_NAME}` : SITE_NAME;
}
setPageTitle("Cart (2 items)");
console.log(document.title);
setPageTitle("");
console.log(document.title);The function builds every title from one pattern, which keeps the format consistent. Call it from your router each time a view changes. For the first output, the console prints Cart (2 items) - Example Store. For the second, it prints Example Store.
State that changes while the user stays on the page can also belong in the title, such as an unread count. Use this sparingly, because a title that changes constantly is noisy in a screen reader.
Where the title goes in the head
The title may appear anywhere inside head. A common choice is directly after the meta charset line. That ordering matters for one reason. The browser must know the encoding before it decodes any non-ASCII bytes. If a title contains characters such as "é" or "日本語" and appears before the charset declaration, the browser may misread it. The charset declaration must sit within the first 1024 bytes of the document. The next chapters on head ordering return to this.
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Café Menu - Example Bistro</title>
</head>Checking your title
You can check a title in three quick ways:
- Read the tab text in the browser.
- Open the developer tools console and type
document.title. This shows what the browser parsed, after whitespace processing and character reference decoding. - Run the page through an HTML validator. It reports a missing
title, an emptytitle, and more than onetitle.
To see how a search engine might display a page, search for the exact URL on the engine, or use its webmaster tools if you have access. Results vary by engine and change over time.
Exercise
A page's source contains <title> Fish & Chips Menu </title> and a script then runs console.log(document.title). What does the console print, and why? Then name one problem with using <title>Menu</title> on every page of a restaurant site.
Show answer
It prints Fish & Chips Menu. The parser decodes & to &, and the document.title getter trims the ends and collapses runs of whitespace into single spaces. A title of "Menu" on every page makes pages indistinguishable in tabs, bookmarks, history, and search results, and it does not name the restaurant. Each page needs its own specific title, for example "Dinner Menu - Example Bistro".
Exercise
You build a single-page app. When the user clicks from the product list to a product, the address bar changes but the tab still says "Example Store". What is wrong, and how do you fix it?
Show answer
The browser did not load a new document, so the original title stays. The router must set document.title on every route change, for example with a setPageTitle("Trail Running Shoes") call. For accessibility, also move focus to the new view's heading or announce the change, so screen reader users know the page changed.