Signup/Sign In
PUBLISHED ON: JULY 29, 2021

How to highlight code in text on a web page using HTML?

Answer: Using <code> and <pre> Tag

The HTML provides a separate tag to add programming code snippets to the web page to format them and show them in a different style than normal text. The code text/snippet has a unique styling that can be included using the HTML <code> and <pre> tag.

Learn about these tags in detail here:

HTML <code> Tag

The <code> tag is generally used to format a single word or a 2-3 word group which are programming-related keywords, or function names, etc. The <code> tag uses fixed spacing, letter size, and fonts.

The <code> tag can be used to add any variables or any fragments of code.

Example: Using <code> tag in HTML

Let us include the <code> tag to add codes to the webpage.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<body>
    <h2>HTML code tag</h2>
	<p> Here in the webpage include <code> printf(), scanf() </code> for sample example</p>
</body>
</html>

Output:

Here is the output of the above program.

HTML code tag example

HTML <pre> Tag

The <code> tag is used to represent only some phases of code to maximum a single line of code. For adding a large multiple-line code snippet within the webpage, we should use the <pre> tag.

Example: Adding multiple line codes in webpage

Here is an example of adding multiple line codes to the webpage using the <pre> tag.

Conclusion

Though we can add codes to the <p> tag. But it will not differentiate between normal text and codes. Use the <code> tag to style the codes and for multiple lines codes add the <code> tag within <pre> tag.



About the author: