How to mark up a code snippet in HTML
Out of habit, let's start by wrapping it in a
However, the HTML spec
pretag represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.
pre tag can contain anything which conveys its semantic meaning at least partly through how its
text is formatted,
like a code snippet, a poem, or an ascii art.
pre tag is not enough to represent a code snippet. How do we distinguish a code snippet from
pre-formatted content? By marking up the snippet with
code, and then wrapping it in a
HTML spec has an answer to that too:
There is no formal way to indicate the language of computer code being marked up. Authors who wish to mark code elements with the language used, e.g. so that syntax highlighting scripts can use the right rules, can use the class attribute, e.g. by adding a class prefixed with "language-" to the element.
In short, assign to the
code tag a class named language-name of the programming language.
There is still one improvement left, which applies to
pre tag in general.
Conveying formatting of a text can be difficult to a visually-challenged user, just like conveying an image is.
In order to assist such a user with an alternate description, wrap such semi-accessible content in a
figure tag, and put
the alternate description in a