What other CSS best practices should I keep in mind (besides removing unused selectors)?


#1

Question

What other CSS best practices should I keep in mind (besides removing unused selectors)?

Answer

Besides keeping your CSS free from unused selectors and declarations keep in mind some other best practices like:

  • making your CSS easy to read, this can be implemented by
    • using comments to describe logical groups of styling, for example a comment that describes a group of footer styling:
/* footer content */
footer {...}
  • keeping whitespace/indentation consistent by placing each selector and declaration on a new line, and indenting each declaration with 2 or 4 spaces:
h1,
h3 {
  color: yellow;
  text-transform: uppercase;
}
  • keeping your CSS DRY (Don’t Repeat Yourself) for more concise code, for example:

    • using class selectors to apply styles to multiple elements at once
    • using shorthand notation when possible (for properties like padding and margin)
  • using the separation of concerns principle to keep your CSS and HTML separate by:

    • avoiding the use of inline styles in HTML
    • avoiding the use of an internal stylesheet (the <style> element)