Bootstrap ยท Chapter 43 of 43

Bootstrap Best Practices

To get the most out of Bootstrap, follow a few key habits: rely on utility classes before writing custom CSS, keep your grid and breakpoints consistent, and always test your layout on multiple screen sizes.

Good Bootstrap habits also include accessibility considerations, like proper ARIA attributes on interactive components, and performance considerations, like only loading the JavaScript components you actually use.

Syntax
// Best practices, not new syntax

Structure and consistency

Always wrap grid rows in a container, stick to the 12-column system rather than fighting it, and prefer utility classes (spacing, flex, colors) over writing new custom CSS whenever possible.

Accessibility and performance

Add aria-label and role attributes to interactive components like navbars and button groups. For production, consider building a custom Bootstrap bundle with only the Sass and JS modules you actually need, to reduce file size.

Example 1 (html)
<nav class="navbar navbar-expand-lg navbar-light bg-light" aria-label="Main navigation">
  <div class="container">
    <a class="navbar-brand" href="#">Site</a>
  </div>
</nav>
Output
A properly labeled navbar that screen readers can identify as the main navigation

Adding aria-label gives assistive technology a clear description of the navbar's purpose.

Example 2 (html)
<div class="d-flex flex-column flex-md-row gap-3 p-3">
  <div class="flex-fill bg-light p-3">Box 1</div>
  <div class="flex-fill bg-light p-3">Box 2</div>
</div>
Output
Two boxes stacked on mobile and placed side by side on medium screens and up, with even spacing

This layout uses only utility classes (flex, gap, responsive breakpoints) instead of custom CSS, following Bootstrap best practices.

Key points

  • Prefer Bootstrap utility classes over writing new custom CSS.
  • Always wrap the grid in containers and follow the 12-column system.
  • Add ARIA attributes to interactive components for accessibility.
  • Build a custom, trimmed-down Bootstrap bundle for better performance in production.
๐Ÿ’ก Note: Reading Bootstrap's official documentation regularly is the best way to stay current, since components and utilities are refined with each release.

๐Ÿ“ Quick Quiz

1. What should you prefer over writing new custom CSS in Bootstrap projects?

2. Why add ARIA attributes to components like navbars?

3. What is a performance best practice for production Bootstrap sites?