CSS Best Practices for Modern Websites

Summary

Writing maintainable and scalable CSS for your projects

Content

CSS Best Practices for Modern Websites

Good CSS architecture helps your project scale and remain maintainable. Here are essential practices.

1. Use CSS Custom Properties

Custom properties (variables) improve maintainability:

:root {
  --primary-color: #ff6600;
  --font-size-base: 13px;
  --spacing-unit: 1rem;
}

.button {
  background-color: var(--primary-color);
  padding: var(--spacing-unit);
  font-size: var(--font-size-base);
}

2. Organize with Methodologies

Choose a methodology like:

  • BEM: Block Element Modifier
  • OOCSS: Object-Oriented CSS
  • SMACSS: Scalable and Modular Architecture
  • ITCSS: Inverted Triangle CSS

3. Use Logical Properties

Logical properties work better with internationalization:

/* Instead of margin-left */
margin-inline-start: 1rem;

/* Instead of padding-right */
padding-inline-end: 0.5rem;

4. Mobile-First Approach

Write for mobile first, then add larger screens:

/* Base styles (mobile) */
.container {
  width: 100%;
}

/* Tablet */
@media (min-width: 768px) {
  .container {
    max-width: 768px;
  }
}

/* Desktop */
@media (min-width: 1024px) {
  .container {
    max-width: 1024px;
  }
}

5. Minimize Specificity

Low specificity makes CSS easier to override:

/* Avoid */
.container .header .nav .link {
  color: blue;
}

/* Prefer */
.nav-link {
  color: blue;
}

6. Use Modern Layouts

Grid and Flexbox simplify layouts:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

Conclusion

Write CSS with scalability in mind. Use modern features, maintain organized structure, and prioritize performance.

Your future self (and teammates) will appreciate well-structured CSS.