CodeBlanks Logo Icon CodeBlanks

Pre and code block

HTML course · Intermediate · Lesson 4/67

Write a preformatted code block with <pre><code>.

pre: preformatted text

The <pre> tag shows preformatted text. Spaces, line breaks and indentation are kept as written. It suits ASCII art, a postal address or a plain text document.

Example: write two lines inside <pre>, with a real line break between them. The browser keeps the lines and the spaces; it does not collapse them. The <p> tag, in contrast, squeezes spaces.

pre around code: a code block

The standard way to write a code block is <pre> wrapping <code>. The <pre> tag keeps indentation and line breaks; the <code> tag adds the meaning 'this is computer code'.

Take a function definition with line breaks and indentation. The function name and body stay indented; line breaks are preserved. A single <code> is enough for one line; a multi-line block needs <pre>.

Exercise Write a code block

Add a <pre> to body; inside it put a <code>. Inside the <code> write a function: line one function greet() {, line two return "Hello";, line three }. Start line two with two spaces.

Show example solution
<body>
  <pre><code>function greet() {
  return "Hello";
}</code></pre>
</body>

Test yourself

  1. What is the main job of the <pre> tag?

    • Colour the text
    • Keep spaces and line breaks
    • Make a link
    • Show an image
    Show answer

    Keep spaces and line breaks — Correct. pre shows preformatted text as written.

  2. Complete code inside pre

    <pre><____>save()</code></pre>
    Show answer
    <pre><code>save()</code></pre>
  3. Match each tag to its role

    <pre>
    Keeps spaces
    <code>
    Code piece
    <p>
    Paragraph
    <br>
    Line break

All lessons in Intermediate