Code snippet of the week - code/pre elements
label code-snippet-of-the-week
label html

Code snippet of the week - code/pre elements

by Edric Chan

Note: This blog post originally appeared on my blog.

Another code snippet! This week, I’ll be covering how to create code snippets with the <code> and <pre> HTML tags.

Note: If you haven’t seen it, I’ve designed a new header image for these kind of posts! Look out for posts with the image on the top of the post!

Getting Started

To get started, ensure that you have a code editor (ideally Visual Studio Code, Sublime Text, Atom, etc.).

  1. Get started by downloading either of the coding editors as stated above (or you can search some online; don’t use your built-in text editor as this may screw things up in the encoding)
  2. Next, open up the code editor and create a new file. We’ll name the file index.html.
  3. Create the bare minimal for an HTML file. Copy the code below:

     <!DOCTYPE html> <!-- This is the line that is required in order for the page to work properly. -->
     <html>
     <head>
         <meta charset="UTF-8">
         <title>Document title</title>
         <!-- I'm a comment! -->
         <!-- Multiline comments
         are<br>
         okay too -->
     </head>
     <body>
         <!-- Your page content goes here -->
         <p>Hello, world!</p>
     </html>
    

Creating code

To create code, surround some text with <code> (which can be optionally nested within a <pre>).

<pre><code>Hello, World! Here is some useful content in a code block!</code></pre>

See the MDN web docs for more info:

Highlight.js Example

This example assumes that you’ve included Highlight.js and that you’ve initialized Highlight.js in your main HTML file.

<pre><code class="lang-html">
    &amp;lt;p&amp;gt;Displaying a code snippet within an actual code snippet? Codeception!&amp;lt;/p&amp;gt;
</code></pre>

Demo

Here’s a working demo for you to play with!

See the Pen Code/ Pre Element by Edric Chan (@Edric03) on CodePen.

About Edric Chan

(site owner)

An 18-year-old teenager who self-taught himself to code at the age of 13 with a 2015 Macbook Pro. Currently pursuing DIT at Singapore Polytechnic.

Share "Code snippet of the week - code/pre elements"

Successfully copied to the clipboard!
An error occurred while attempting to copy to the clipboard