Cette traduction est en cours.

Un des buts principaux de HTML est de structurer du texte et lui donner du sens (ce que l'on appelle la sémantique) afin que le navigateur puisse l-afficher correctement. Cet article explique comment HTML peut être utilisé pour structurer une page en ajouter des titres et des paragraphes, marquer des emphases, créer des listes, et autres.

Pré-requis:

Être familiarisé avec HTML, traité sur la page Commencer avec le HTML.

Objectif:

Apprendre comment ajouter des balises dans une page de texte simple pour la structurer et lui donner du sens — en incluant des paragraphes, des titres, des listes, des emphases et des citations.

Les bases : Titres et paragraphes

La plupart des textes structurés comprennent des titres et des paragraphes, que ce soit dans les romans, les journaux, les livres scolaires, les magazines et ainsi de suite.

An example of a newspaper front cover, showing use of a top level heading, subheadings and paragraphs.

Le contenu structuré facilite la lecture et la rend plus agréable.

En HTML, les paragraphes doivent être contenus dans un élément <p>, comme ceci :

<p>Je suis un paragraphe.</p>

Chaque titre doit être contenu dans un élément titre :

<h1>Je suis le titre de l'histoire.</h1>

Il y a 6 éléments de titre — <h1>, <h2>, <h3>, <h4>, <h5>, et <h6>. Chaque élément représente un niveau de titre différent ; <h1> représente le titre principal, <h2> représente un sous-titre, <h3> représente un sous-sous-titre, et ainsi de suite jusqu'au niveau de titre le plus bas <h6>.

Implémentation de la hiérarchie structurale

Dans une histoire, <h1> représenterait le titre de l'histoire, les <h2> représenteraient les titres des chapitres et <h3> les sous-sections des chapitres et ainsi de suite.

<h1>Heidi</h1>

<p>De Johanna Spyri</p>

<h2>Chapitre I : En route pour l'alpe.</h2>

<p>Quand on quitte le riant village de Mayenfeld pour gravir la montagne ...</p>

<h2>Chapitre II : Chez le grand-père.</h2>

<p>Quand la cousine Dete eut disparu, le Vieux se rassit sur le banc et commença à tirer de sa pipe ...</p>

<h3>Chapitre III : Sur l'alpage.</h3>

<p>Le lendemain matin, un coup de sifflet aigu réveilla Heidi. Lorsqu'elle ouvrit les yeux, ...</p>

C'est vous qui décidez ce que représente les éléments utilisés tant que la hiérarchie a du sens. Vous devez cependant garder à l'esprit quelques bonnes pratiques lorsque vous créez de telles structures :

  • Il est préférable de n'utiliser qu'un seul <h1> par page — c'est le niveau principal, et tous les autres devraient être de niveau inférieur.
  • Assurez-vous d'utiliser les titres dans l'ordre correct et logique : <h1> puis <h2>, puis <h3> et ainsi de suite.
  • Bien qu'il y ait 6 niveaux de titre (de <h1> à <h6>), vous ne devriez pas utiliser plus de trois niveaux dans une page. Les documents avec beaucoup de niveaux deviennt complexe et difficile à parcourir. Dans ce cas, il est préférable de partager le contenu sur plusieurs pages.

Pourquoi  faut-il structurer un document ?

Pour répondre à cette question, regardons la page text-start.html — le point de départ de l'exemple que nous allons utiliser dans cet article (une recette). Enregistrez une copie de ce fichier sur votre ordinateur car vous en aurez besoin pour les exercices qui vont suivre. Le corps de ce document contient plusieurs parties qui ne sont pas "marquées" d'une quelconque manière, mais séparées par des retours à la ligne (obtenus en appuyant sur la touche « Entrée » « ⏎ »)

Cependant, si l'on ouvre ce document dans dans un navigateur, il apparaît comme un gros bloque de texte !

A webpage that shows a wall of unformatted text, because there are no elements on the page to structure it.

Ceci est dû au fait qu'il n'y a aucun élément, ou aucune information, qui permet au navigateur de savoir ce qu'est le titre et quels textes sont des paragraphes. De plus :

  • Les visiteurs d'une page web regardent très brièvement la page pour trouver du contenu intéressant, et souvent ne lisent que les titres (article en anglais : How Long Do Users Stay on Web Pages?). S'ils ne trouvent pas le contenu souhaité en quelques secondes, ils seront probablement frustrés et chercheront l'information souhaitée ailleurs.
  • Les moteurs de recherche, lorsqu'ils indexent votre page, utilisent les titres pour influer sur le classement de votre page lors de recherche. Sans titre, votre page ne sera pas indexée correctement (voir SEO (Search Engine Optimization).
  • Les personnes malvoyantes ne pouvant lire votre page peuvent utiliser des lecteurs d'écran. Ces logiciels permettent d'accéder rapidement à une partie du texte. Pour cela, ils lisent les titres de votre document aux utilisateurs, leur permettant ainsi de trouver l'information dont ils ont besoin rapidement. Si les titres ne sont pas disponibles, les lecteurs d'écran lisent tout le document, le rendant peu accessible aux personnes avec un handicape visuel.
  • Pour ajouter du style au contenu CSS, ou pour rendre votre page dynamique JavaScript, vous devez marquer le document avec des éléments, ce qui permet ensuite de les cibler avec CSS/JavaScript.

Il est donc nécessaire d'ajouter de la structure au document en utilisant des balises.

Apprentissage actif : structurer le contenu

Dans l'exemple ci-dessous, ajoutez des éléments dans le texte brut du champ Input afin qu'il apparaisse comme un titre et deux paragraphes dans le champ Output.

Si vous faites une erreur, vous pouvez recommencer en appuyant sur le bouton Reset. Si vous êtes bloqués, appuyez sur le bouton Show solution pour afficher la réponse.

Why do we need semantics?

Semantics are relied on everywhere around us — we rely on previous experience to tell us what the function of everyday objects is; when we see something, we know what its function will be. So, for example, we expect a red traffic light to mean "stop", and a green traffic light to mean "go". Things can get tricky very quickly if the wrong semantics are applied (do any countries use red to mean "go"? I hope not.)

In a similar vein, we need to make sure we are using the correct elements, giving our content the correct meaning, function, or appearance. In this context the <h1> element is also a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page."

<h1>This is a top level heading</h1>

By default, the browser will give it a large font size to make it look like a heading (although you could style it to look like anything you wanted using CSS). More importantly, its semantic value will be used in multiple ways, for example by search engines and screen readers (as mentioned above.)

On the other hand, you could make any element look like a top level heading. Consider the following:

<span style="font-size: 32px; margin: 21px 0;">Is this a top level heading?</span>

This is a <span> element. It has no semantics. You use it to wrap content when you want to apply CSS to it (or do something to it with JavaScript) without giving it any extra meaning (You'll find out more about these later on in the course.) We've applied some CSS to it to make it look like a top level heading, but since it has no semantic value, it will not get any of the extra benefits described above. It is a good idea to use the relevant HTML element for the job.

Lists

Now let's turn our attention to lists. Lists are everywhere in life — from your shopping list to the list of directions you subconsciously follow to get to your house every day, to the lists of instructions you are following in these tutorials! Lists are everywhere on the Web too, and we've got three different types to worry about.

Unordered

Unordered lists are used to mark up lists of items for which the order of the items doesn't matter — let's take a shopping list as an example.

milk
eggs
bread
hummus

Every unordered list starts off with a <ul> element — this wraps around all the list items:

<ul>
milk
eggs
bread
hummus
</ul>

The last step is to wrap each list item in a <li> (list item) element:

<ul>
  <li>milk</li>
  <li>eggs</li>
  <li>bread</li>
  <li>hummus</li>
</ul>

Active learning: Marking up an unordered list

Try editing the live sample below to create your very own HTML unordered list.

Ordered

Ordered lists are lists in which the order of the items does matter — let's take a set of directions as an example:

Drive to the end of the road
Turn right
Go straight across the first two roundabouts
Turn left at the third roundabout
The school is on your right, 300 meters up the road

The markup structure is the same as for unordered lists, except that you have to wrap the list items in an <ol> element, rather than <ul>:

<ol>
  <li>Drive to the end of the road</li>
  <li>Turn right</li>
  <li>Go straight across the first two roundabouts</li>
  <li>Turn left at the third roundabout</li>
  <li>The school is on your right, 300 meters up the road</li>
</ol>

Active learning: Marking up an ordered list

Try editing the live sample below to create your very own HTML ordered list.

Active learning: Marking up our recipe page

So at this point in the article, you have all the information you need to mark up our recipe page example. You can choose to either save a local copy of our text-start.html starting file and do the work there, or do it in the editable example below. Doing it locally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page. Both have pros and cons.

If you get stuck, you can always press the Show solution button, or check out our text-complete.html example on our github repo.

Nesting lists

It is perfectly ok to nest one list inside another one. You might want to have some sub-bullets sitting below a top level bullet. Let's take the second list from our recipe example:

<ol>
  <li>Remove the skin from the garlic, and chop coarsely.</li>
  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
  <li>Add all the ingredients into a food processor.</li>
  <li>Process all the ingredients into a paste.</li>
  <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
  <li>If you want a smooth hummus, process it for a longer time.</li>
</ol>

Since the last two bullets are very closely related to the one before them (they read like sub-instructions or choices that fit below that bullet), it might make sense to nest them inside their own unordered list, and put that list inside the current fourth bullet. This would look like so:

<ol>
  <li>Remove the skin from the garlic, and chop coarsely.</li>
  <li>Remove all the seeds and stalk from the pepper, and chop coarsely.</li>
  <li>Add all the ingredients into a food processor.</li>
  <li>Process all the ingredients into a paste.
    <ul>
      <li>If you want a coarse "chunky" hummus, process it for a short time.</li>
      <li>If you want a smooth hummus, process it for a longer time.</li>
    </ul>
  </li>
</ol>

Try going back to the previous active learning example and updating the second list like this.

Emphasis and importance

In human language, we often emphasise certain words to alter the meaning of a sentence, and we often want to mark certain words as important or different in some way. HTML provides various semantic elements to allow us to mark up textual content with such effects, and in this section, we'll look at a few of the most common ones.

Emphasis

When we want to add emphasis in spoken language, we stress certain words, subtly altering the meaning of what we are saying. Similarly, in written language we tend to stress words by putting them in italics. For example, the following two sentences have different meanings.

I am glad you weren't late.

I am glad you weren't late.

The first sentence sounds genuinely relieved that the person wasn't late. In contrast, the second one sounds sarcastic or passive-aggressive, expressing annoyance that the person arrived a bit late.

In HTML we use the <em> (emphasis) element to mark up such instances. As well as making the document more interesting to read, these are recognised by screen readers and spoken out in a different tone of voice. Browsers style this as italic by default, but you shouldn't use this tag purely to get italic styling. To do that, you'd use a <span> element and some CSS, or perhaps an <i> element (see below.)

<p>I am <em>glad</em> you weren't <em>late</em>.</p>

Strong importance

To emphasize important words, we tend to stress them in spoken language and bold them in written language. For example:

This liquid is highly toxic.

I am counting on you. Do not be late!

In HTML we use the <strong> (strong importance) element to mark up such instances. As well as making the document more useful, again these are recognized by screen readers and spoken in a different tone of voice. Browsers style this as bold text by default, but you shouldn't use this tag purely to get bold styling. To do that, you'd use a <span> element and some CSS, or perhaps a <b> element (see below.)

<p>This liquid is <strong>highly toxic</strong>.</p>

<p>I am counting on you. <strong>Do not</strong> be late!</p>

You can nest strong and emphasis inside one another if desired:

<p>This liquid is <strong>highly toxic</strong> —
if you drink it, <strong>you may <em>die</em></strong>.</p>

Active learning: Let's be important!

In this active learning section, we have provided an editable example. Inside it, we'd like you to try adding emphasis and strong importance to the words you think need them, just to have some practice.

Italic, bold, underline...

The elements we've discussed so far have clearcut associated semantics. The situation with <b>, <i>, and <u> is somewhat more complicated. They came about so people could write bold, italics, or underlined text in an era when CSS was still supported poorly or not at all. Elements like this, which only affect presentation and not semantics, are known as presentational elements and should no longer be used, because as we've seen before, semantics is so important to accessibility, SEO, etc.

HTML5 redefined <b>, <i> and <u> with new, somewhat confusing, semantic roles.

Here's the best rule of thumb: it's likely appropriate to use <b>, <i>, or <u> to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. However, it always remains critical to keep an accessibility mindset. The concept of italics isn't very helpful to people using screen readers, or to people using a writing system other than the Latin alphabet.

  • <i> is used to convey a meaning traditionally conveyed by italic: Foreign words, taxonomic designation, technical terms, a thought...
  • <b> is used to convey a meaning traditionally conveyed by bold: Key words, product names, lead sentence...
  • <u> is used to convey a meaning traditionally conveyed by underline: Proper name, misspelling...

A kind warning about underline: People strongly associate underlining with hyperlinks. Therefore, on the Web, it's best to underline only links. Use the <u> element when it's semantically appropriate, but consider using CSS to change the default underline to something more appropriate on the Web. The example below illustrates how it can be done.

<!-- scientific names -->
<p>
  The Ruby-throated Hummingbird (<i>Archilochus colubris</i>)
  is the most common hummingbird in Eastern North America.
</p>

<!-- foreign words -->
<p>
  The menu was a sea of exotic words like <i lang="uk-latn">vatrushka</i>,
  <i lang="id">nasi goreng</i> and <i lang="fr">soupe à l'oignon</i>.
</p>

<!-- a known misspelling -->
<p>
  Someday I'll learn how to <u>spel</u> better.
</p>

<!-- Highlight keywords in a set of instructions -->
<ol>
  <li>
    <b>Slice</b> two pieces of bread off the loaf.
  </li>
  <li>
    <b>Insert</b> a tomato slice and a leaf of
    lettuce between the slices of bread.
  </li>
</ol>

Summary

That's it for now! This article should have given you a good idea of how to start marking up text in HTML, and introduced you to some of the most important elements in this area. There are a lot more semantic elements to cover in this area, and we'll look at a lot more in our 'More Semantic Elements' article, later on in the course. In the next article, we'll be looking in detail at how to create hyperlinks, possibly the most important element on the Web.

 

In this module

 

Étiquettes et contributeurs liés au document

 Contributeurs à cette page : clamb, Ilphrin
 Dernière mise à jour par : clamb,