Code snippet of the week - code/pre elements

Code snippet of the week - code/pre elements

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 (@EdricChan03) on CodePen.

View Demo

About Edric Chan

(site owner)

A 16-year-old tech enthusiast since getting his first MacBook Pro 2015 in the year-end of 2015. When he's not at school, he usually works on small programming projects or reads technology-related books. He currently studies at School of Science & Technology, Singapore and will graduate in 2019 to pursue his post-secondary life.

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

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