Notes on HTML and CSS Coding Practices

Over the Christmas break of my MRes year (pre-first year of PhD), I studied the book Learn to Code HTML & CSS by Shay Howe. It was one of the best tutorials to get one started with these web design languages. I hope to use the knowledge gained to style this very website to my liking.

The final chapter of the book pertains to the best HTML and CSS coding practices. I summarise them here for personal reference. All rights remain with the original author.

The book has been made available on this website.

HTML Coding Practices

  • Write Standards-Compliant Markup. ID attributes should only be used once, otherwise opt for a class. Remember to close elements.
  • Make Use of Semantic Elements. Such as headers, paragraphs, etc.
  • Use the Proper Document Structure.
  • Keep the Syntax Organised.
    • Lowercase letters within element names, attributes and values.
    • Indent nested elements
    • Double quotes only.
    • Remove forward slash at the end of self-closing elements.
    • Omit the values on Boolean attributes.
  • Use Practical ID and Class Values. These values should relate to the content itself, but not the actual style. For example, compare a class named "alert" versus "red".
  • Use the Alternative Text Attribute on Images (i.e. alt). This should still be included and left blank so screen readers don't end up reading the name of the image file. If an image does not have a meaningful value, it should be included as a CSS background image.
  • Separate Content from Style.
  • Avoid Excessive Use of div Elements.
  • Continually Evolve Code.

CSS Coding Practices

  • Organise Codes with Comments. Provide these before each group.
  • Write CSS using Multiple Lines and Spaces. Space after the selector and before the opening {. Space after the colon : within a declaration, and end it with a semicolon ;.
  • Proper Class Names based on the content and not appearance. Modular as possible. Lower case and use hyphens.
  • Build Proficient Selectors. The longer a selector, the higher its specificity values. Try to avoid IDs, use classes when possible. Nest them to only two to three levels deep ideally.
  • Use Specific Classes When Necessary If a CSS selector is so long and specific (e.g. section aside h1 em), it creates a performance lag. It also only applies to a very specific case, so why not use a class to offset the em element here?
  • Shorthand Properties & Values are preferred, as well as Shorthand Hexadecimal Color Values.
  • Drop Units from Zero Values. The percentage sign in 0% is redundant, for example.
  • Group and Align Vendor Prefixes.
  • Modularise Styles for Reuse, and avoid classes with too much redundancy.