Examples of Clean HTML Code

When writing HTML, strict adherence to specific formatting rules and the exact sequence of opening and closing tags is not a prerequisite for the code to run. However, clarity, elegance, and readability are crucial for ongoing maintenance and support.

HTML Examples

Consider an example of “messy” code:

<!DOCTYPE html>
<html>
<head><title>My First Page</title></head>
<body><h1>Welcome!</h1><p>This is a test.</p></body>
</html>

And compare it with a “clean” and readable version:

<!DOCTYPE html>
<html>
<head>
   <title>My First Page</title>
</head>
<body>
   <h1>Welcome!</h1>
   <p>This is a test.</p>
</body>
</html>

The difference is obvious: structured code is easier to read and maintain.

Block-Level and Inline Elements

All HTML elements can be divided into two broad categories: block-level and inline. Block-level elements occupy the full width of their parent container and stack vertically, even if they are written on a single line in the source code:

<h2>Learning HTML</h2><div>HTML is fun.</div>

Result:

Learning HTML
HTML is fun.

Inline elements, by contrast, are laid out on the same line:

<span>Inline</span> <span>elements</span>

Result:

Inline elements

Nested Elements and Indentation

Some tags serve as containers for other tags. For example, <html> contains <head>, <body>, <style>, <script>, and so on. It is important to use proper indentation and line breaks to convey element nesting.

Some developers choose not to indent <head> and <body> because it is obvious they are children of <html>. Nevertheless, for readability, it is better to maintain consistent indentation:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Example Page</title>
</head>
<body>
    <header>
       <h1>Example Page</h1>
    </header>
    <main>
       <section>
           <p>Sample text here.</p>
       </section>
    </main>
</body>
</html>

Typically, indentation uses 2 or 4 spaces. Most code editors handle this automatically.

Line Breaks

Line breaks are generally applied to block-level elements. The content and closing tags of short elements such as <li> or <title> do not necessarily need to be placed on separate lines:

<ul>
      <li>Languages
            <ul>
                <li>Python</li>
                <li>JavaScript</li>
                <li>Ruby</li>
            </ul>
      </li>
</ul>

Writing clean, readable code not only demonstrates care for colleagues and future readers of your code, but also reflects your professional pride and passion for the craft. A structured approach to HTML authoring makes the development process more efficient and enjoyable.

Оцените статью