How to Write Code Blocks in HTML

Rajeev Baniya Feb 02, 2024
  1. Wrap the <code> Tag and Its Contents Inside the <pre> Tag to Write Code Block in HTML
  2. Use the <code> Tag and the CSS white-space Property to Write Code Block in HTML
How to Write Code Blocks in HTML

This article will introduce a few methods of writing blocks of code snippets in HTML.

Wrap the <code> Tag and Its Contents Inside the <pre> Tag to Write Code Block in HTML

The <code> tag defines a piece of computer code. The content inside is displayed in the browser’s default monospace font.

The tag is used to represent code blocks in HTML. The tag is an inline tag.

It means that if we write code snippets inside the <code> tag, the contents inside of the tag are displayed in a line. It does not preserve line breaks or spaces.

The <pre> tag defines preformatted text. Any text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks.

The text or contents inside the <pre> tag will be displayed as written exactly in the HTML source code. The <pre> tag is a block-level element.

If we wrap the <code> tag and its contents inside the <pre> tag, the contents inside the <code> tag will behave as a block-level element. The contents will have the monospace font, and the line breaks and spaces of the code snippets will also be preserved.

For example, write some JavaScript code and wrap the code inside the <code> tag. Next, wrap the <code> element with a <pre> tag.

Example Code:

<p>Code snippet for addition of two numbers in javascript</p>
<pre>
  <code>
    function add (a,b) {
    sum = a + b;
    return sum;
    }
  </code>
</pre>

The above example will display the JavaScript code block.

Use the <code> Tag and the CSS white-space Property to Write Code Block in HTML

In this method, we will seek a replacement for the <pre> tag using some CSS styles. Previously, we knew the <code> element was an inline element.

We used the <pre> tag to make it a block-level element. But, we can also make the <code> tag a block-level element by setting its display property to block.

And we can preserve the line breaks and spaces of the code tag by setting its white-space property to pre-wrap. As a result, it will display code snippets as written in HTML source code.

Thus, we will be able to create code blocks in HTML.

For example, create a <code> tag and write some JavaScript code snippet inside it. Give the <code> tag a class name of the sum.

In CSS, select the sum class and set the display property to block and the white-space property to pre-wrap.

Example code:

<code class="sum">
  function (a, b) {
  sum = a + b;
  return sum;
  }
</code>
.sum {
  display: block;
  white-space: pre-wrap;
}

The code examples above will produce a JavaScript code block.

Related Article - HTML Tag