HTML

Monospaced Font


Monospaced fonts, also known as fixed-width or non-proportional fonts, are fonts in which each character takes up the same amount of horizontal space. These fonts are commonly used for displaying code, creating text art, or aligning text columns.

 

Using the <code> Tag

The <code> tag is used to display code snippets in a monospaced font. It is semantically meaningful for representing code.

<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Monospaced Font Example</title>
</head>
<body>
    <p>Here is some <code>inline code</code> in a monospaced font.</p>
</body>
</html>

 

Using the <pre> Tag

The <pre> tag preserves both spaces and line breaks, displaying text in a monospaced font. It is useful for preformatted text.

<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Preformatted Text Example</title>
</head>
<body>
    <pre>
This is preformatted text.
    It preserves spaces and line breaks.
</pre>
</body>
</html>

 

Using the <samp> Tag

The <samp> tag is used to represent sample output from a computer program, typically rendered in a monospaced font.

<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Sample Output Example</title>
</head>
<body>
    <p>Here is some sample output: <samp>Error: File not found</samp></p>
</body>
</html>

 

Key Points

  1. Semantic Meaning: Use <code>, <pre>, and <samp> tags when displaying code, preformatted text, or sample output respectively, for semantic clarity.
  2. No CSS Needed: These tags inherently apply a monospaced font, so no additional CSS is necessary.

 

Example Combining All Methods

Here is an example demonstrating the use of the <code>, <pre>, and <samp> tags for monospaced text:

<!DOCTYPE html>
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Monospaced Font Example</title>
</head>
<body>
    <p>Here is some <code>inline code</code> in a monospaced font.</p>
    <pre>
This is preformatted text.
    It preserves spaces and line breaks.
    </pre>
    <p>Here is some sample output: <samp>Error: File not found</samp></p>
</body>
</html>