🏷️ #frontend #html #css

HTML & CSS Best Practices

Congratulations on reaching the final chapter of this course! By now, you should have the skills to design and develop a responsive static webpage using HTML and CSS. In this chapter, we will delve into the best practices of writing HTML and CSS to ensure that your web designs are efficient, maintainable, and adhering to industry standards.

Before we continue, please consider buying the e-book version of this course.

By purchasing this e-book, you will get access to all the accompanied source code. Thank you for your support! Happy coding! 🖥️✨

Purchase e-book || Download a sample

1. Use semantic HTML tags #

When creating an HTML document, you should always use semantic tags whenever you can. Meaning you should use <header> to define the header, <main> for the main content, <side> for the sidebar, <footer> for the footer, and so on.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
  <head>
    <title>Use semantic tags</title>
  </head>
  <body>
    <header>
      <nav>. . .</nav>
    </header>

    <main>
      <p>Lorem ipsum dolor . . .</p>
    </main>

    <footer>
      <p>&copy; 2023 My Website. All rights reserved.</p>
    </footer>
  </body>
</html>

These elements provide more descriptive names for different sections of your webpage, making it easier for you, the browser, and the search engine to understand the structure and purpose of the content. This is why using semantic tags can also improve your website’s SEO (Search Engine Optimization) score.

Some developers have a habit of using class names to represent the purpose of the element like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
  <head>
    <title>Use div and class</title>
  </head>
  <body>
    <div class="header">
      <div class="nav">. . .</div>
    </div>

    <div class="main">
      <p>Lorem ipsum dolor . . .</p>
    </div>

    <div class="footer">
      <p>&copy; 2023 My Website. All rights reserved.</p>
    </div>
  </body>
</html>

There is nothing wrong with this technique, but since the class naming is very flexible, the browser and search engine won’t be able to understand them.

2. Maintain clear indentation and formatting #

You should also make sure that both your HTML and CSS code are properly formatted. Formatting your code improves the readability, making it easier for future maintenance. For example, this is an example of poorly formatted code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html>
  <head>
    <title>Sample HTML Page</title>
  </head>
  <body>
    <p>Lorem ipsum dolor. . .</p>
    <p>Lorem ipsum dolor. . .</p>
  </body>
</html>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}
h1 {
  color: red;
  font-size: 36px;
}
.header {
  background-color: #333333;
  color: white;
}
.nav {
  width: 100%;
  background-color: #444444;
  padding: 10px;
}
.nav ul {
  margin: 0;
  padding: 0;
}
.nav li {
  display: inline;
  margin-right: 10px;
}
.nav a {
  text-decoration: none;
  color: white;
}
.main {
  margin: 20px;
  padding: 10px;
}
.footer {
  background-color: #333333;
  color: white;
  text-align: center;
}
.footer p {
  margin: 0;
}

As you can see, even though they are readable for your browser, it is difficult for humans to comprehend. It will be better if you add clear indentations and line breaks.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html>
  <head>
    <title>Sample HTML Page</title>
  </head>

  <body>
    <p>. . .</p>
    <p>. . .</p>
  </body>
</html>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

h1 {
  color: red;
  font-size: 36px;
}

.header {
  background-color: #333333;
  color: white;
}

. . . .footer {
  background-color: #333333;
  color: white;
  text-align: center;
}

.footer p {
  margin: 0;
}

This can be easily achieved by using the right code editor such as VSCode, which has the formatting functionality built-in, created on top of js-beautify . I also recommend the Auto Complete Tag extension, which automatically adds the closing tag for your HTML elements if needed.

However, sometimes, you’ll want a minified version of the CSS file to improve the performance of your webpage. In this case, you could create an automated system using PostCSS , where you edit the input file, apply transformations and optimizations, and generate a minified output effortlessly.

3. Comment your code #

As your project gets bigger, it will be easy for you to forget the original intention of a random piece of code. Commenting your code makes comprehending the code’s purpose, structure, and logic much more effortless. Especially when you are working in a team setting, comments make sure that your team members understand the code correctly, allowing for effective debugging, troubleshooting, and collaboration.

Comments in HTML have the following format. Comments will not be displayed in the browser:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <title>Comments</title>
  </head>

  <body>
    <p>Lorem ipsum dolor . . .</p>
    <!-- This is an HTML comment and won't be displayed in the browser -->
    <p>Lorem ipsum dolor . . .</p>
  </body>
</html>

You can also add multi-line comments:

1
2
3
4
<!--
    This is a multi-line comment in HTML,
    Lorem ipsum dolor . . .
-->

For CSS:

1
2
3
4
/* This is a CSS comment */
body {
  background-color: #f0f0f0; /* Background color for body */
}
1
2
3
4
/*
  This is a multi-line comment in CSS,
  Lorem ipsum dolor . . .
*/

4. Ensure accessibility and responsiveness #

When designing your webpages, you should keep in mind that the webpages might be used by different audiences, and you should take measures to ensure that it is accessible to all of them.

For example, you should always add descriptive text for images using the alt attribute. This attribute will be used by the screen reader, and it will be displayed if the image does not load for some reason.

You should also make sure there is a clear contrast between the content and the background. This will improve readability, especially for those with visual impairments. Avoid using color alone to express messages.

Interactive elements on your webpage should also provide clear feedback to users. You need to be comfortable using the pseudo-selectors such as :hover, :focus, and so on. For example, when a user interacts with a button by clicking on it, the button’s appearance should change. Maybe by adopting a slightly darker color, to indicate that the interaction has been registered.

There are many other techniques you could employ depending on your specific requirements, such as creating a table of contents for long webpages, avoiding autoplay for video and audio content, etc. Check out the Web Content Accessibility Guidelines for more information.

5. The <head> section is important #

We focused primarily on the <body> section in this course, but in fact, the <head> section is just as important and should not be neglected, especially for SEO purposes. You should always make sure that the following information is included in the <head> section of your HTML document.

  • Document title

    1
    
    <title>Your page title</title>
    

    This title will be displayed in the browser’s tab title and also used by the search engine. If the search engine indexes your webpage, the title will be displayed as the search result.

    google search title

  • Description

    1
    
    <meta name="description" content="Brief description of your page content" />
    

    The description will not be displayed in the browser, but it is used by search engines.

    google search description

  • Keywords

    1
    
    <meta name="keywords" content="keyword1, keyword2, keyword3" />
    

    Keywords are used by search engines to analyze the intent and purpose of webpage content. They allow the users to discover and access your webpage through search engines.

    However, nowadays, search engines are a lot smarter. It will also analyze the title, description, as well as the content itself to find the best keywords.

  • Viewport

    As we discussed before, specifying a viewport makes sure the webpage is mobile-friendly, which is a significant factor in modern SEO.

    1
    
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
  • Author

    Specifying the author of the content can add credibility. This information is sometimes used by search engines as well.

    1
    
    <meta name="author" content="Author Name" />
    
  • Robots

    The robots tag tells search engines how to handle the webpage. It tells the search engine whether to index the page, follow its link, or neither.

    1
    
    <meta name="robots" content="index, follow" />
    
  • Include CSS files

    The CSS files should also be included in the <head> section, making sure the styles are loaded before the content. Users can see a styled webpage while it is still loading, providing a better user experience.

    1
    
    <link rel="stylesheet" href="styles.css" />
    
  • Canonical link

    If the content is originally published elsewhere, the <head> section should also include a canonical tag pointing to the original content.

    1
    
    <link rel="canonical" href="https://example.com/your-page" />
    
  • Open Graph Protocol (OGP) tags

    Open Graph tags provide metadata that social media platforms use when your page is shared, making sure the social preview has all the necessary information and is visually appealing.

    1
    2
    3
    4
    5
    6
    7
    
    <meta property="og:title" content="Your Page Title" />
    <meta
      property="og:description"
      content="Brief description of your page content"
    />
    <meta property="og:image" content="https://example.com/image.jpg" />
    <meta property="og:url" content="https://example.com/your-page" />
    

6. Separate your files #

In our chapter on recreating YouTube using HTML and CSS, we put everything together on one CSS file, but in fact, that is not a good habit when creating a real-world project. Instead, you should modularize your code by putting only related styles in one file.

For instance, instead of styles.css, you could have base.css for some common styles, form.css for all form components, table.css for all table components, and so on.

You should also create a clear and logical file structure to organize your CSS files. You can have separate folders for different types of CSS files.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
.
├── overrides
│   └── overrides.css
├── styles
│   ├── base
│   │   └── base.css
│   ├── components
│   │   ├── button.css
│   │   └── modal.css
│   ├── layout
│   │   ├── header.css
│   │   ├── footer.css
│   │   └── sidebar.css
│   ├── utilities
│   │   ├── spacing.css
│   │   ├── typography.css
│   │   └── animations.css
│   └── vendor
│       └── normalize.css
└── themes
    ├── light-theme.css
    └── dark-theme.css

In a production environment, you should make sure the browser makes as few HTTP requests as possible. You could use tools such as PostCSS to concatenate, minify, and optimize CSS files for production. Your HTML file should only import the final optimized CSS file, not the whole thing.

7. Choose meaningful class and ID names #

Choosing descriptive names for your classes and IDs makes it easier for you and other members of your team to understand the purpose and styling associated with each element.

1
2
3
4
<section id="about" class="about-section">
  <h2 class="section-heading">About Us</h2>
  <p class="section-content">Lorem ipsum dolor sit amet . . .</p>
</section>

8. Keep selectors simple #

When we first discussed the selectors, we used some complex examples like:

1
div.container > p ~ a {. . .}

This is not a good thing to do in a real project, as it will become a huge trouble for future maintenance. You should always keep your selectors simple and easy to understand.

If you need to use combinator selectors, make sure it is easy and trackable. In this above example, it is best to give the <a> element a proper class name, perhaps .container-link, and use a basic class selector instead.

9. Keep a consistent style #

Keeping a consistent style provides a better user experience and simplifies maintenance. When users visit your website, they usually expect a unified visual presentation across different pages. A consistent style in terms of colors, fonts, spacing, and layout ensures that the website appears polished and professional.

To ensure a consistent style, you should avoid hardcoding values, and instead use variables and the var() function we talked about previously.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
:root {
  --primary-color: #3498db;
  --secondary-color: #e67e22;
  --base-spacing: 1rem;
}

.button {
  background-color: var(--secondary-color);
  . . .
}

If you are working in a team setting, you should make sure you and your team members follow a well-defined and agreed-upon style guide. Also, conduct regular code reviews to ensure that everyone is following the established style guidelines. Any inconsistencies should be addressed during these reviews.

10. Pay attention to browser compatibility #

Not all CSS properties are well supported across all browsers on the market. Sometimes, you need to use vendor prefixes to ensure compatibility. Vendor prefixes are a mechanism used by browsers during the implementation of new or experimental CSS properties.

Luckily, you don’t have to search browser support for every CSS property you write. This can be automatically taken care of using PostCSS and the autoprefixer plugin.

Conclusion #

Congratulations on completing this course on HTML and CSS! You’ve taken the first step towards mastering the fundamentals of web development. With the knowledge gained from this course, you can now create stunning websites that are both visually appealing and functionally sound.

To continue building your skills, I highly recommend checking out the e-book version of this course. It includes the complete source code for all the examples mentioned in the course. Whether you’re a beginner or an experienced developer, this e-book is an essential resource for anyone looking to take their web development skills to the next level. So why wait? Get your hands on this e-book today and start building amazing websites like a pro!

Purchase E-book

It’s also important to keep in mind that the best practices mentioned in this chapter are simply guidelines. They’re not set in stone and you’re always welcome to share your thoughts and suggestions in the comments section below. Your input is valuable and can help us all learn and grow together.


If you think my articles are helpful, please consider making a donation to me. Your support is greatly appreciated.

Subscribe to my newsletter ➡️

✅ News and tutorials every other Monday

✅ Unsubscribe anytime

✅ No spam. Always free.