Best Practices for Writing HTML and CSS

Congratulations! Now we have covered everything you need to know about HTML and CSS. By now, you should have the skills to design and develop a responsive static webpage using these technologies.

In this lesson, we will delve into the best practices of writing HTML and CSS code to ensure that your webpage designs are efficient, maintainable, and adhering to industry standards.

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.

html
1<!DOCTYPE html>
2<html>
3  <head>
4    <title>Use semantic tags</title>
5  </head>
6  <body>
7    <header>
8      <nav>. . .</nav>
9    </header>
10
11    <main>
12      <p>Lorem ipsum dolor . . .</p>
13    </main>
14
15    <footer>
16      <p>&copy; 2023 My Website. All rights reserved.</p>
17    </footer>
18  </body>
19</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.

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

html
1<!DOCTYPE html>
2<html>
3  <head>
4    <title>Use div and class</title>
5  </head>
6  <body>
7    <div class="header">
8      <div class="nav">. . .</div>
9    </div>
10
11    <div class="main">
12      <p>Lorem ipsum dolor . . .</p>
13    </div>
14
15    <div class="footer">
16      <p>&copy; 2023 My Website. All rights reserved.</p>
17    </div>
18  </body>
19</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:

Open demo in new tab

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.

html
1<!DOCTYPE html>
2<html>
3  <head>
4    <title>Sample HTML Page</title>
5  </head>
6
7  <body>
8    <p>. . .</p>
9    <p>. . .</p>
10  </body>
11</html>
css
1body {
2  font-family: Arial, sans-serif;
3  margin: 0;
4  padding: 0;
5}
6
7h1 {
8  color: red;
9  font-size: 36px;
10}
11
12.header {
13  background-color: #333333;
14  color: white;
15}
16
17. . . .footer {
18  background-color: #333333;
19  color: white;
20  text-align: center;
21}
22
23.footer p {
24  margin: 0;
25}

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.

We 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 for production use.

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 it easy for you and future maintainers to understand the original purpose of the code. 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:

html
1<!DOCTYPE html>
2<html>
3  <head>
4    <title>Comments</title>
5  </head>
6
7  <body>
8    <p>Lorem ipsum dolor . . .</p>
9    <!-- This is an HTML comment and won't be displayed in the browser -->
10    <p>Lorem ipsum dolor . . .</p>
11  </body>
12</html>

You can also add multi-line comments:

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

For CSS:

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

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 clicks on a button, its appearance should change. Maybe by adopting a slightly darker color, to indicate that the click action 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
html
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
html
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
html
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.

html
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.

html
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.

html
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.

html
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.

html
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.

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

6. Separate your files

In our lesson 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.

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

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

8. Keep selectors simple

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

css
1div.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 then 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 do that, you should avoid hardcoding values, and instead use variables and the var() function we talked about previously.

css
1:root {
2  --primary-color: #3498db;
3  --secondary-color: #e67e22;
4  --base-spacing: 1rem;
5}
6
7.button {
8  background-color: var(--secondary-color);
9  . . .
10}

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.