Comprehensive Bootstrap 5 Framework Cheatsheet: The Ultimate Development Guide

Introduction: What is Bootstrap Framework?

Bootstrap is a powerful, feature-rich frontend toolkit for building responsive websites and applications. Developed by Twitter, it has evolved into the world’s most popular CSS framework that combines:

  • A responsive grid system for flexible layouts
  • Pre-styled components for rapid UI development
  • Utility classes for quick styling
  • JavaScript plugins for interactive elements
  • Customization options through Sass variables
  • Cross-browser compatibility and modern design principles

This cheatsheet covers everything from setup to advanced features to help you leverage Bootstrap’s full potential.

Getting Started with Bootstrap

Installation Methods

MethodCommand/CodeBest for
CDN<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">Quick prototyping, small projects
npmnpm install bootstrap@5.3.2Webpack/Node.js projects
Yarnyarn add bootstrap@5.3.2Alternative package manager
Composercomposer require twbs/bootstrap:5.3.2PHP projects
DownloadDownload from getbootstrap.comOffline development

Basic Template

 
html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Template</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
    
    <!-- Optional JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  </body>
</html>

Required Meta Tags

  • <meta charset="utf-8"> – Character encoding
  • <meta name="viewport" content="width=device-width, initial-scale=1"> – Responsive viewport settings

Bootstrap CSS Architecture

File Structure

FilePurpose
bootstrap.cssComplete, unminified CSS
bootstrap.min.cssComplete, minified CSS (production)
bootstrap-grid.cssGrid system only
bootstrap-reboot.cssReboot styles only
bootstrap-utilities.cssUtility classes only
bootstrap.rtl.cssRight-to-left support

Box-sizing Model

Bootstrap uses box-sizing: border-box globally, meaning padding and border are included in element width/height calculations.

Reboot Styles

Bootstrap’s Reboot module normalizes CSS across browsers and sets sensible defaults:

  • Uses native font stack
  • Removes margins from headings
  • Styles links consistently
  • Normalizes form elements
  • Provides a clean baseline for further styling

Responsive Breakpoints System

Media Query Ranges

BreakpointInfixDimensionsDevice Class
Extra smallNone< 576pxPortrait phones
Smallsm≥ 576pxLandscape phones
Mediummd≥ 768pxTablets
Largelg≥ 992pxDesktops
Extra largexl≥ 1200pxLarge desktops
Extra extra largexxl≥ 1400pxLarger desktops

Breakpoint Mixins (Sass)

 
scss
// Example usage
@include media-breakpoint-up(md) {
  // Styles for medium (md) screens and up
}

@include media-breakpoint-down(lg) {
  // Styles for less than large (lg) screens
}

@include media-breakpoint-between(sm, lg) {
  // Styles for between small and large screens
}

Container System

Container Types

ClassBehaviorUse Case
.containerFixed-width container that changes max-width at each breakpointStandard layouts
.container-fluidFull width container (100%)Edge-to-edge designs
.container-{breakpoint}100% width until specified breakpoint, then behaves like .containerResponsive hybrid approaches

Container Max Widths

BreakpointContainer Max-Width
xs (< 576px)100%
sm (≥ 576px)540px
md (≥ 768px)720px
lg (≥ 992px)960px
xl (≥ 1200px)1140px
xxl (≥ 1400px)1320px

Grid System Architecture

Grid Classes

ClassPurpose
.rowContainer for columns, creates negative margins
.colEqual-width columns
.col-{size}Specific column width (1-12)
.col-{breakpoint}-{size}Responsive column widths
.col-autoWidth based on content

Grid Behavior

  • Built on flexbox
  • 12-column system
  • Supports nesting
  • Supports horizontal alignment
  • Supports vertical alignment
  • Supports column ordering and offsetting

Column Wrapping

Columns wrap to the next line when their total exceeds 12 units:

 
html
<div class="row">
  <div class="col-9">col-9</div>
  <div class="col-4">col-4 (wraps to next line)</div>
  <div class="col-6">col-6</div>
</div>

Row Columns

Control the number of columns per row:

 
html
<div class="row row-cols-2">
  <!-- Creates 2 equal-width columns per row -->
  <div class="col">Column 1</div>
  <div class="col">Column 2</div>
  <div class="col">Column 3 (new row)</div>
  <div class="col">Column 4 (new row)</div>
</div>

Sass System

Importing Bootstrap Sass

 
scss
// Import all of Bootstrap
@import "node_modules/bootstrap/scss/bootstrap";

// Or import parts of Bootstrap
@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";
@import "node_modules/bootstrap/scss/grid";

Customizing Variables

 
scss
// Required
@import "node_modules/bootstrap/scss/functions";

// Override default variables
$primary: #0074d9;
$border-radius: 0.5rem;
$enable-rounded: false;

// Required
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/maps";
@import "node_modules/bootstrap/scss/mixins";
@import "node_modules/bootstrap/scss/root";

// Import components
@import "node_modules/bootstrap/scss/bootstrap";

Key Customizable Variables

CategoryExample VariableDescription
Colors$primary, $secondary, etc.Theme colors
Spacing$spacerBase spacing unit
Typography$font-family-base, $font-size-baseFont settings
Borders$border-width, $border-radiusBorder properties
Components$input-btn-padding-yComponent-specific settings
Grid$grid-columns, $grid-gutter-widthGrid configuration
Enable flags$enable-rounded, $enable-shadowsToggle features

Color System

 
scss
// Theme colors
$primary:       #0d6efd;
$secondary:     #6c757d;
$success:       #198754;
$info:          #0dcaf0;
$warning:       #ffc107;
$danger:        #dc3545;
$light:         #f8f9fa;
$dark:          #212529;

// Grayscale colors
$gray-100: #f8f9fa;
$gray-900: #212529;

// Color functions
$blue-100: tint-color($blue, 80%);
$blue-900: shade-color($blue, 80%);

Sass Maps

 
scss
// Color map
$theme-colors: (
  "primary":    $primary,
  "secondary":  $secondary,
  "success":    $success,
  "info":       $info,
  "warning":    $warning,
  "danger":     $danger,
  "light":      $light,
  "dark":       $dark
);

// Spacer map
$spacers: (
  0: 0,
  1: $spacer * .25,    // 4px
  2: $spacer * .5,     // 8px
  3: $spacer,          // 16px
  4: $spacer * 1.5,    // 24px
  5: $spacer * 3,      // 48px
);

Custom CSS with Utility API

 
scss
$utilities: (
  "cursor": (
    property: cursor,
    values: auto pointer grab,
  ),
  "custom-width": (
    property: width,
    class: w,
    values: (
      25: 25%,
      33: 33.333%,
      66: 66.666%,
    )
  )
);

CSS Variables (Custom Properties)

Bootstrap uses CSS variables for theming, accessible in plain CSS:

 
css
.custom-element {
  background-color: var(--bs-primary);
  border-radius: var(--bs-border-radius);
  padding: var(--bs-4);
}

Root Variables

 
css
:root {
  --bs-blue: #0d6efd;
  --bs-primary: var(--bs-blue);
  --bs-body-font-family: var(--bs-font-sans-serif);
  --bs-border-radius: 0.375rem;
}

JavaScript Features

JavaScript Components

ComponentInitializationDescription
Alertnew bootstrap.Alert(el)Dismissible alerts
Buttonnew bootstrap.Button(el)Button states
Carouselnew bootstrap.Carousel(el, options)Image slider
Collapsenew bootstrap.Collapse(el, options)Toggleable content
Dropdownnew bootstrap.Dropdown(el, options)Dropdown menus
Modalnew bootstrap.Modal(el, options)Dialog boxes
Offcanvasnew bootstrap.Offcanvas(el, options)Sidebars/panels
Popovernew bootstrap.Popover(el, options)Rich tooltips
ScrollSpynew bootstrap.ScrollSpy(el, options)Automatic nav highlighting
Tabnew bootstrap.Tab(el)Togglable tabs
Toastnew bootstrap.Toast(el, options)Notifications
Tooltipnew bootstrap.Tooltip(el, options)Simple tooltips

Data Attribute API

Bootstrap components can be initialized with data attributes instead of JavaScript:

 
html
<!-- Instead of JS: new bootstrap.Modal(document.getElementById('myModal')) -->
<button data-bs-toggle="modal" data-bs-target="#myModal">Launch modal</button>

Component Options

Set options via data attributes or JavaScript:

 
html
<!-- Via data attribute -->
<button data-bs-toggle="tooltip" data-bs-placement="top" title="Tooltip text">Hover me</button>

<!-- Via JavaScript -->
<script>
  new bootstrap.Tooltip(document.querySelector('#example'), {
    placement: 'top',
    trigger: 'hover focus'
  });
</script>

Event Handling

 
javascript
// Listen for events
const myModal = document.getElementById('myModal')
myModal.addEventListener('show.bs.modal', event => {
  // Do something before modal shows
})

// Trigger events programmatically
const modal = new bootstrap.Modal(document.getElementById('myModal'))
modal.show() // Shows the modal
modal.hide() // Hides the modal

Common Events

ComponentEvents
Modalshow.bs.modal, shown.bs.modal, hide.bs.modal, hidden.bs.modal
Collapseshow.bs.collapse, shown.bs.collapse, hide.bs.collapse, hidden.bs.collapse
Alertclose.bs.alert, closed.bs.alert
Carouselslide.bs.carousel, slid.bs.carousel
Dropdownshow.bs.dropdown, shown.bs.dropdown, hide.bs.dropdown, hidden.bs.dropdown

Icon System

Bootstrap Icons is a separate library but integrates perfectly with Bootstrap:

Installation

 
html
<!-- CSS-based icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

Usage Examples

 
html
<!-- Icon font -->
<i class="bi bi-heart-fill"></i>

<!-- SVG icons -->
<svg class="bi" width="32" height="32" fill="currentColor">
  <use xlink:href="bootstrap-icons.svg#heart-fill"/>
</svg>

<!-- As background image -->
<div class="bi bi-heart-fill"></div>

Utility Pattern System

Core Utility Categories

CategoryExample ClassesUsage
Spacingm-3, p-2, mt-lg-5Margin and padding
Colortext-primary, bg-successText and background colors
Flexd-flex, flex-row, justify-content-betweenFlexbox layouts
Gridg-3, gx-md-5Grid gutters
Positionposition-relative, fixed-topElement positioning
Sizingw-50, h-100, mw-100Width and height
Texttext-center, text-md-startText alignment and styling
Borderborder, border-primary, roundedBorder style and radius
Shadowshadow, shadow-lgBox shadows
Displayd-none, d-sm-blockResponsive display

Utility API Customization

The Utility API in Sass allows creation of custom utilities:

 
scss
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/utilities";

$utilities: map-merge(
  $utilities,
  (
    "viewport-height": (
      property: height,
      class: vh,
      values: (
        25: 25vh,
        50: 50vh,
        75: 75vh,
        100: 100vh,
      )
    ),
  )
);

@import "bootstrap/scss/utilities/api";

Form Validation and Controls

HTML Form Validation

 
html
<form class="needs-validation" novalidate>
  <div class="mb-3">
    <label for="email" class="form-label">Email</label>
    <input type="email" class="form-control" id="email" required>
    <div class="invalid-feedback">
      Please provide a valid email.
    </div>
    <div class="valid-feedback">
      Looks good!
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit</button>
</form>

<script>
  // Enable validation
  (() => {
    'use strict'
    const forms = document.querySelectorAll('.needs-validation')
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }
        form.classList.add('was-validated')
      }, false)
    })
  })()
</script>

Validation States

StateClassesEffect
Validis-valid, .valid-feedbackGreen input with success message
Invalidis-invalid, .invalid-feedbackRed input with error message
Validation upon submissionneeds-validation, was-validatedValidate on submit

Custom Form Controls

ControlClassesDescription
Switchesform-check form-switchToggle switches
Rangeform-rangeSlider controls
File inputsform-controlFile selectors
Input groupsinput-groupCombined form elements
Floating labelsform-floatingLabels that float on focus

Advanced Grid Techniques

Auto-Layout Columns

 
html
<!-- Equal-width columns -->
<div class="row">
  <div class="col">Equal</div>
  <div class="col">Equal</div>
  <div class="col">Equal</div>
</div>

<!-- Column with specific width -->
<div class="row">
  <div class="col">Auto</div>
  <div class="col-6">6 units</div>
  <div class="col">Auto</div>
</div>

Column Ordering

 
html
<!-- Order classes -->
<div class="row">
  <div class="col order-3">First in DOM, displayed third</div>
  <div class="col order-1">Second in DOM, displayed first</div>
  <div class="col order-2">Third in DOM, displayed second</div>
</div>

<!-- Responsive ordering -->
<div class="row">
  <div class="col order-md-2">First on mobile, second on desktop</div>
  <div class="col order-md-1">Second on mobile, first on desktop</div>
</div>

Offsetting Columns

 
html
<!-- Fixed offset -->
<div class="row">
  <div class="col-md-4">col-md-4</div>
  <div class="col-md-4 offset-md-4">col-md-4 offset-md-4</div>
</div>

<!-- Responsive offset -->
<div class="row">
  <div class="col-sm-5 col-md-6">col-sm-5 col-md-6</div>
  <div class="col-sm-5 offset-sm-2 col-md-6 offset-md-0">col-sm-5 offset-sm-2 col-md-6 offset-md-0</div>
</div>

Nesting

 
html
<div class="row">
  <div class="col-sm-8">
    Level 1: col-sm-8
    <div class="row">
      <div class="col-sm-6">Level 2: col-sm-6</div>
      <div class="col-sm-6">Level 2: col-sm-6</div>
    </div>
  </div>
  <div class="col-sm-4">Level 1: col-sm-4</div>
</div>

Accessibility Features

ARIA Attributes

Bootstrap components include appropriate ARIA attributes:

 
html
<!-- Example of Modal with ARIA -->
<div class="modal" tabindex="-1" 
    role="dialog" 
    aria-labelledby="modalTitle" 
    aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalTitle">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
    </div>
  </div>
</div>

Screen Reader Utilities

 
html
<!-- Visually hidden but available to screen readers -->
<span class="visually-hidden">Instructions for screen reader users.</span>

<!-- Screen reader only text for controls -->
<button class="btn btn-primary">
  <i class="bi bi-envelope"></i>
  <span class="visually-hidden">Email</span>
</button>

<!-- Hide from screen readers -->
<div aria-hidden="true">
  Decorative content
</div>

Keyboard Navigation

  • Tab through focusable elements
  • Escape key closes modals and other popups
  • Arrow keys control carousels
  • Space/Enter for buttons and interactive elements

Content Optimization

Responsive Typography

 
html
<!-- Responsive headings -->
<h1 class="display-1">Display 1</h1>
<h1 class="display-6">Display 6</h1>

<!-- Responsive font sizes (RFS) -->
<div class="fs-1">Large text</div>
<div class="fs-6">Small text</div>

Responsive Images

 
html
<!-- Responsive image (maximum width 100%) -->
<img src="..." class="img-fluid" alt="...">

<!-- Image thumbnails -->
<img src="..." class="img-thumbnail" alt="...">

<!-- Aligning images -->
<img src="..." class="float-start" alt="...">
<img src="..." class="mx-auto d-block" alt="...">

Responsive Embeds

 
html
<!-- Responsive embed (16:9 ratio) -->
<div class="ratio ratio-16x9">
  <iframe src="https://www.youtube.com/embed/zpOULjyy-n8" title="YouTube video" allowfullscreen></iframe>
</div>

<!-- Other aspect ratios -->
<div class="ratio ratio-1x1">
  <iframe src="..."></iframe>
</div>
<div class="ratio ratio-4x3">
  <iframe src="..."></iframe>
</div>
<div class="ratio ratio-21x9">
  <iframe src="..."></iframe>
</div>

Common Challenges and Solutions

Vertical Centering

 
html
<!-- Using flex utilities -->
<div class="d-flex align-items-center" style="height: 200px;">
  <div>Vertically centered</div>
</div>

<!-- Using position utilities -->
<div class="position-relative" style="height: 200px;">
  <div class="position-absolute top-50 start-50 translate-middle">
    Centered element
  </div>
</div>

Card Grids with Equal Height

 
html
<div class="row row-cols-1 row-cols-md-3 g-4">
  <div class="col">
    <div class="card h-100">
      <div class="card-body">
        <h5 class="card-title">Card 1</h5>
        <p class="card-text">Short content</p>
      </div>
    </div>
  </div>
  <div class="col">
    <div class="card h-100">
      <div class="card-body">
        <h5 class="card-title">Card 2</h5>
        <p class="card-text">This card has more content than Card 1.</p>
      </div>
    </div>
  </div>
  <!-- More cards -->
</div>

Sticky Footer

 
html
<body class="d-flex flex-column min-vh-100">
  <header>
    <!-- Header content -->
  </header>
  
  <main class="flex-grow-1">
    <!-- Page content -->
  </main>
  
  <footer>
    <!-- Footer content -->
  </footer>
</body>

Responsive Behavior Control

 
html
<!-- Hide on small, show on medium and up -->
<div class="d-none d-md-block">
  Visible on medium and larger screens
</div>

<!-- Show on small, hide on medium and up -->
<div class="d-block d-md-none">
  Visible only on small screens
</div>

<!-- Show on print only -->
<div class="d-none d-print-block">
  This appears only when printed
</div>

Build System and Tools

Bootstrap CLI (via npm scripts)

 
json
// package.json
{
  "scripts": {
    "css": "sass --style expanded scss/main.scss css/main.css",
    "css-minify": "sass --style compressed scss/main.scss css/main.min.css",
    "watch": "sass --watch scss/main.scss:css/main.css",
    "serve": "browser-sync start --server --files 'css/*.css, *.html'",
    "dev": "npm-run-all --parallel watch serve"
  }
}

Compiling with Node.js

 
javascript
const sass = require('sass');
const fs = require('fs');
const path = require('path');

// Compile Bootstrap with custom variables
const result = sass.renderSync({
  file: path.resolve('scss/custom.scss'),
  outputStyle: 'compressed'
});

fs.writeFileSync(path.resolve('css/custom.min.css'), result.css);

Webpack Configuration

 
javascript
// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(scss)$/,
        use: [
          {
            // Adds CSS to the DOM by injecting a `<style>` tag
            loader: 'style-loader'
          },
          {
            // Interprets `@import` and `url()` like `import/require()`
            loader: 'css-loader'
          },
          {
            // Loader for webpack to process CSS with PostCSS
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: () => [
                  require('autoprefixer')
                ]
              }
            }
          },
          {
            // Loads a SASS/SCSS file and compiles it to CSS
            loader: 'sass-loader'
          }
        ]
      }
    ]
  }
};

Best Practices and Tips

  1. Performance Optimization
    • Use only required components: Import only needed Bootstrap components
    • Purge unused CSS with tools like PurgeCSS
    • Lazy-load components with JavaScript
    • Optimize images with responsive utilities
  2. Customization Strategy
    • Create a single custom.scss file for all Bootstrap overrides
    • Override variables instead of writing custom CSS
    • Use CSS Custom Properties for runtime theming
    • Follow SASS architecture: variables → maps → mixins → components
  3. Mobile-First Development
    • Start with mobile layouts first
    • Use responsive breakpoint utilities strategically
    • Test on real devices frequently
    • Optimize touch targets (min 44x44px)
  4. Accessibility Implementation
    • Maintain proper heading hierarchy
    • Use semantic HTML elements
    • Include appropriate ARIA attributes
    • Ensure keyboard navigation works
    • Test with screen readers
  5. Maintainability Tips
    • Document custom components
    • Follow Bootstrap’s naming conventions
    • Group related custom components
    • Use meaningful class names for custom elements

Resources for Further Learning

  1. Official Documentation
  2. Learning Resources
  3. Tools
  4. Community Support

Remember that Bootstrap is designed to be both a complete framework and a starting point. It’s highly customizable to fit your project needs while maintaining a consistent design system that scales well across devices.

Scroll to Top