How do you display preformatted text (like code snippets) in HTML
•7 min read
To display preformatted text such as code snippets in HTML, you can use the <pre> and <code> tags together.
✅ Explanation
- The
<pre>tag preserves whitespace, tabs, and line breaks — it shows text exactly as written in the HTML. - The
<code>tag semantically indicates that the text inside is computer code.
💻 Example Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preformatted Text Example</title>
<style>
pre {
background-color: #f4f4f4;
padding: 10px;
border-radius: 6px;
font-size: 16px;
border: 1px solid #ccc;
overflow-x: auto;
}
</style>
</head>
<body>
<h2>Displaying Preformatted Code in HTML</h2>
<pre><code>
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Salesforce Developer");
</code></pre>
</body>
</html>
JavaScript🧠 How It Works
<pre>ensures the text appears exactly as typed (spaces and new lines are preserved).<code>identifies it as code, which helps browsers and screen readers understand the context.
⚡ Bonus Tip
If you’re showing code on a webpage (like tutorials or documentation), you can also use syntax highlighting libraries such as:
- Prism.js
- Highlight.js


