Pseudo-classes et pseudo-éléments

Cette traduction est incomplète. Aidez-nous à traduire cet article depuis l’anglais

Voyons maintenant les sélecteurs de pseudo-classes et de pseudo-éléments. Il en existe un grand nombre, ces sélecteurs sont souvent assez spécifiques. Une fois que vous aurez compris comment les utiliser, revenez consulter leur liste pour voir si quelque chose peut fonctionner dans la tâche que vous essayez d'accomplir. Une fois encore, vérifiez la prise en charge par les navigateurs sur la page MDN associée à chaque sélecteur.

Prérequis : Maîtrise élémentaire de l'informatique, suite logicielle de base installée, compétences élémentaires pour travailler avec des fichiers, connaissance de base du HTML  (cf. Introduction à HTML), et une idée de Comment fonctionne CSS.
Objectif : Découvrir les sélecteurs de pseudo-classes et de pseudo-éléments.

Qu'est ce qu'une pseudo-classe ?

Une pseudo-classe est un sélecteur ciblant des éléments dans un état spécifique, par ex. le premier élément d'un type, ou un élément survolé par le pointeur de la souris. Leur comportement correspond à celui du'ne classe, mais qui ne s'appliquerait que partiellement. On gagne ainsi en flexibilité, en éliminant du code inutile. Le résultat est plus facile à maintenir.

Les pseudo-classes sont signalées par un mot clé commençant par deux points :

:pseudo-class-name

Exemple d'une pseudo-classe élémentaire 

Voyons cela dans un premier exemple. Pour agrandir et mettre en gras le texte du premier paragraphe d'un article, on pourrait attribuer une classe à ce paragraphe, puis lui ajouter du CSS, comme ci-dessous :

Mais cette solution est difficile à maintenir — que se passe-t-il si un nouveau paragraphe est ajouté en haut du document ? Il faut dans ce cas déplacer manuellement la classe vers le nouveau paragraphe. Une solution plus souple est d'utiliser le sélecteur de pseudo-classe : first-child — cela cible dans tous les cas le premier élément enfant de l'article : plus nécessaire d'éditer le code HTML (particulièrement utile en particulier quand le code HTML est généré par un CMS.)

Toutes les pseudo-classes se comportent de la même manière. Elles ciblent les éléments du document dans un état donné, comme si vous aviez ajouté une classe dans votre code HTML. Jetez un œil à quelques exemples sur MDN :

Pseudo-classes d'action utilisateur

Certaines pseudo-classes ne s'appliquent que lorsque l'utilisateur interagit avec le document d'une manière ou d'une autre. Ces pseudo-classes d'action utilisateur, parfois appelées pseudo-classes dynamiques, agissent comme si une classe avait été ajoutée à l'élément lorsque l'utilisateur interagit avec lui. Par exemple :

:hover — mentionné ci-dessus ; s'applique quand l'utilisateur déplace son pointeur sur un élément, généralement un lien.
:focus — s'applique uniquement si l'utilisateur concentre l'élément à l'aide des commandes du clavier.

Qu'est ce qu'un pseudo-élément ?

Pseudo-elements behave in a similar way, however they act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements. Pseudo-elements start with a double colon ::.

::pseudo-element-name

Note : Some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or examples. Modern browsers support the early pseudo-elements with single- or double-colon syntax for backwards compatibility.

For example, if you wanted to select the first line of a paragraph you could wrap it in a <span> element and use an element selector; however, that would fail if the number of words you had wrapped were longer or shorter than the parent element's width. As we tend not to know how many words will fit on a line — as that will change if the screen width or font-size changes — it is impossible to robustly do this by adding HTML.

The ::first-line pseudo-element selector will do this for you reliably — if the number of words increases and decreases it will still only select the first line.

It acts as if a <span> was magically wrapped around that first formatted line, and updated each time the line length changed.

You can see that this selects the first line of both paragraphs.

Combiner pseudo-classes et pseudo-éléments

If you wanted to make the first line of the first paragraph bold you could chain the :first-child and ::first-line selectors together. Try editing the previous live example so it uses the following CSS. We are saying that we want to select the first line, of the first <p> element, which is inside an <article> element.

article p:first-child::first-line { 
  font-size: 120%; 
  font-weight: bold; 
}

Generating content with ::before and ::after

There are a couple of special pseudo-elements, which are used along with the content property to insert content into your document using CSS.

You could use these to insert a string of text, such as in the live example below. Try changing the text value of the content property and see it change in the output. You could also change the ::before pseudo-element to ::after and see the text inserted at the end of the element instead of the beginning.

Inserting strings of text from CSS isn't really something we do very often on the web however, as that text is inaccessible to some screen readers and might be hard for someone to find and edit in the future.

A more valid use of these pseudo-elements is to insert an icon, for example the little arrow added in the example below, which is a visual indicator that we wouldn't want read out by a screenreader:

These pseudo-elements are also frequently used to insert an empty string, which can then be styled just like any element on the page.

In this next example, we have added an empty string using the ::before pseudo-element. We have set this to display: block in order that we can style it with a width and height. We then use CSS to style it just like any element. You can play around with the CSS and change how it looks and behaves.

The use of the ::before and ::after pseudo-elements along with the content property is referred to as "Generated Content" in CSS, and you will often see this technique being used for various tasks. A great example is the site CSS Arrow Please, which helps you to generate an arrow with CSS. Look at the CSS as you create your arrow and you will see the ::before and ::after pseudo-elements in use. Whenever you see these selectors, look at the content property to see what is being added to the document.

Section de référence

Il existe un grand nombre de pseudo-classes et pseudo-éléments, une bonne liste de références est donc utile. Vous trouverez ci-dessous des tableaux les répertoriant, avec pour chacun le lien vers la page de référence sur MDN. Vous y trouverez toutes les informations sur leur utilisation.

Pseudo-classes

Sélecteur Description
:active Matches when the user activates (for example clicks on) an element.
:any-link Matches both the :link and :visited states of a link.
:blank Matches an <input> element whose input value is empty.
:checked Matches a radio button or checkbox in the selected state.
:current Matches the element, or an ancestor of the element, that is currently being displayed.
:default Matches the one or more UI elements that are the default among a set of similar elements.
:dir Select an element based on its directionality (value of the HTML dir attribute or CSS direction property).
:disabled Matches user interface elements that are in an disabled state.
:empty Matches an element that has no children except optionally white space.
:enabled Matches user interface elements that are in an enabled state.
:first In Paged Media, matches the first page.
:first-child Matches an element that is first among its siblings.
:first-of-type Matches an element which is first of a certain type among its siblings.
:focus Matches when an element has focus.
:focus-visible Matches when an element has focus and the focus should be visible to the user.
:focus-within Matches an element with focus plus an element with a descendent that has focus.
:future Matches the elements after the current element.
:hover Matches when the user hovers over an element.
:indeterminate Matches UI elements whose value is in an indeterminate state, usually checkboxes.
:in-range Matches an element with a range when its value is in-range.
:invalid Matches an element, such as an <input>, in an invalid state.
:lang Matches an element based on language (value of the HTML lang attribute).
:last-child Matches an element which is last among its siblings.
:last-of-type Matches an element of a certain type that is last among its siblings.
:left In Paged Media, matches left-hand pages.
:link Matches unvisited links.
:local-link Matches links pointing to pages that are in the same site as the current document.
:is() Matches any of the selectors in the selector list that is passed in.
:not Matches things not matched by selectors that are passed in as a value to this selector.
:nth-child Matches elements from a list of siblings — the siblings are matched by a formula of the form an+b (e.g. 2n + 1 would match elements 1, 3, 5, 7, etc. All the odd ones.)
:nth-of-type Matches elements from a list of siblings that are of a certain type (e.g. <p> elements) — the siblings are matched by a formula of the form an+b (e.g. 2n + 1 would match that type of element, numbers 1, 3, 5, 7, etc. All the odd ones.)
:nth-last-child Matches elements from a list of siblings, counting backwards from the end. The siblings are matched by a formula of the form an+b (e.g. 2n + 1 would match the last element in the sequence, then two elements before that, then two elements before that, etc. All the odd ones, counting from the end.)
:nth-last-of-type Matches elements from a list of siblings that are of a certain type (e.g. <p> elements), counting backwards from the end. The siblings are matched by a formula of the form an+b (e.g. 2n + 1 would match the last element of that type in the sequence, then two elements before that, then two elements before that, etc. All the odd ones, counting from the end.)
:only-child Matches an element that has no siblings.
:only-of-type Matches an element that is the only one of its type among its siblings.
:optional Matches form elements that are not required.
:out-of-range Matches an element with a range when its value is out of range.
:past Matches the elements before the current element.
:placeholder-shown Matches an input element that is showing placeholder text.
:playing Matches an element representing an audio, video, or similar resource that is capable of being “played” or “paused”, when that element is “playing”.
:paused Matches an element representing an audio, video, or similar resource that is capable of being “played” or “paused”, when that element is “paused”.
:read-only Matches an element if it is not user-alterable.
:read-write Matches an element if it is user-alterable.
:required Matches form elements that are required.
:right In Paged Media, matches right-hand pages.
:root Matches an element that is the root of the document.
:scope Matches any element that is a scope element.
:valid Matches an element such as an <input> element, in a valid state.
:target Matches an element if it is the target of the current URL (i.e. if it has an ID matching the current URL fragment).
:visited Matches visited links.

Pseudo-éléments

Sélecteur Description
::after Matches a stylable element appearing after the originating element's actual content.
::before Matches a stylable element appearing before the originating element's actual content.
::first-letter Matches the first letter of the element.
::first-line Matches the first line of the containing element.
::grammar-error Matches a portion of the document containing a grammar error as flagged by the browser.
::selection Matches the portion of the document that has been selected.
::spelling-error Matches a portion of the document containing a spelling error as flagged by the browser.

Dans ce cours

  1. Cascade and inheritance
  2. CSS selectors
  3. The box model
  4. Backgrounds and borders
  5. Handling different text directions
  6. Overflowing content
  7. Values and units
  8. Sizing items in CSS
  9. Images, media, and form elements
  10. Styling tables
  11. Debugging CSS
  12. Organizing your CSS