HTML for Web Development

0% completed

Previous
Next
HTML - Code Element

In this lesson, you'll learn how to mark up computer code and other text that should appear in a fixed-width font. This is important when you want to show examples of code or denote a technical term.

What Is the HTML <code> Element?

The <code> element is used to display computer code, commands, or any text that should be set off as code. When you use <code>, the text is usually shown in a monospace (fixed-width) font, so it is clear and distinct from regular text.

Basic Syntax:

<code>Your code here</code>

Example:

<p>To print "Hello, World!" in Python, you can use the following code:</p> <code>print("Hello, World!")</code>

The <pre> Element

The <pre> element tells the browser to preserve both whitespace and line breaks in the text. This is useful for displaying code blocks exactly as you write them.

Syntax:

<pre> Your text or code here with spaces and line breaks. </pre>

Example:

<pre> def greet(name): print("Hello, " + name + "!") greet("Alice") </pre>

Additional Elements for Code and Technical Text

1. <samp> Element

The <samp> element is used to represent sample output from a computer program or system. It often appears in a monospace font.

Example:

<p>When you run the program, you may see output like:</p> <samp>Hello, World!</samp>

2. <kbd> Element

The <kbd> element is used to denote keyboard input or instructions. It helps show which keys a user might press.

Example:

<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy text.</p>

Combining Elements for Clear Examples

You can mix these elements to present code, output, and instructions together.

Example: A Full Code Block with Output and Instructions

HTML

. . . .

Explanation:

  • The <code> element marks the code snippet.
  • The <pre> element preserves the formatting and indentation.
  • The <samp> element shows what the output might look like.
  • The <kbd> element indicates the keys a user might press in the command line.

These elements help present technical content clearly and are essential tools when writing about programming or system commands. Practice using these tags to display code examples accurately in your HTML pages.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next