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
| Method | Command/Code | Best for |
|---|---|---|
| CDN | <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> | Quick prototyping, small projects |
| npm | npm install bootstrap@5.3.2 | Webpack/Node.js projects |
| Yarn | yarn add bootstrap@5.3.2 | Alternative package manager |
| Composer | composer require twbs/bootstrap:5.3.2 | PHP projects |
| Download | Download from getbootstrap.com | Offline development |
Basic Template
<!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
| File | Purpose |
|---|---|
| bootstrap.css | Complete, unminified CSS |
| bootstrap.min.css | Complete, minified CSS (production) |
| bootstrap-grid.css | Grid system only |
| bootstrap-reboot.css | Reboot styles only |
| bootstrap-utilities.css | Utility classes only |
| bootstrap.rtl.css | Right-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
| Breakpoint | Infix | Dimensions | Device Class |
|---|---|---|---|
| Extra small | None | < 576px | Portrait phones |
| Small | sm | ≥ 576px | Landscape phones |
| Medium | md | ≥ 768px | Tablets |
| Large | lg | ≥ 992px | Desktops |
| Extra large | xl | ≥ 1200px | Large desktops |
| Extra extra large | xxl | ≥ 1400px | Larger desktops |
Breakpoint Mixins (Sass)
// 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
| Class | Behavior | Use Case |
|---|---|---|
.container | Fixed-width container that changes max-width at each breakpoint | Standard layouts |
.container-fluid | Full width container (100%) | Edge-to-edge designs |
.container-{breakpoint} | 100% width until specified breakpoint, then behaves like .container | Responsive hybrid approaches |
Container Max Widths
| Breakpoint | Container 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
| Class | Purpose |
|---|---|
.row | Container for columns, creates negative margins |
.col | Equal-width columns |
.col-{size} | Specific column width (1-12) |
.col-{breakpoint}-{size} | Responsive column widths |
.col-auto | Width 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:
<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:
<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
// 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
// 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
| Category | Example Variable | Description |
|---|---|---|
| Colors | $primary, $secondary, etc. | Theme colors |
| Spacing | $spacer | Base spacing unit |
| Typography | $font-family-base, $font-size-base | Font settings |
| Borders | $border-width, $border-radius | Border properties |
| Components | $input-btn-padding-y | Component-specific settings |
| Grid | $grid-columns, $grid-gutter-width | Grid configuration |
| Enable flags | $enable-rounded, $enable-shadows | Toggle features |
Color System
// 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
// 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
$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:
.custom-element {
background-color: var(--bs-primary);
border-radius: var(--bs-border-radius);
padding: var(--bs-4);
}Root Variables
: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
| Component | Initialization | Description |
|---|---|---|
| Alert | new bootstrap.Alert(el) | Dismissible alerts |
| Button | new bootstrap.Button(el) | Button states |
| Carousel | new bootstrap.Carousel(el, options) | Image slider |
| Collapse | new bootstrap.Collapse(el, options) | Toggleable content |
| Dropdown | new bootstrap.Dropdown(el, options) | Dropdown menus |
| Modal | new bootstrap.Modal(el, options) | Dialog boxes |
| Offcanvas | new bootstrap.Offcanvas(el, options) | Sidebars/panels |
| Popover | new bootstrap.Popover(el, options) | Rich tooltips |
| ScrollSpy | new bootstrap.ScrollSpy(el, options) | Automatic nav highlighting |
| Tab | new bootstrap.Tab(el) | Togglable tabs |
| Toast | new bootstrap.Toast(el, options) | Notifications |
| Tooltip | new bootstrap.Tooltip(el, options) | Simple tooltips |
Data Attribute API
Bootstrap components can be initialized with data attributes instead of JavaScript:
<!-- 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:
<!-- 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
// 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 modalCommon Events
| Component | Events |
|---|---|
| Modal | show.bs.modal, shown.bs.modal, hide.bs.modal, hidden.bs.modal |
| Collapse | show.bs.collapse, shown.bs.collapse, hide.bs.collapse, hidden.bs.collapse |
| Alert | close.bs.alert, closed.bs.alert |
| Carousel | slide.bs.carousel, slid.bs.carousel |
| Dropdown | show.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
<!-- CSS-based icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">Usage Examples
<!-- 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
| Category | Example Classes | Usage |
|---|---|---|
| Spacing | m-3, p-2, mt-lg-5 | Margin and padding |
| Color | text-primary, bg-success | Text and background colors |
| Flex | d-flex, flex-row, justify-content-between | Flexbox layouts |
| Grid | g-3, gx-md-5 | Grid gutters |
| Position | position-relative, fixed-top | Element positioning |
| Sizing | w-50, h-100, mw-100 | Width and height |
| Text | text-center, text-md-start | Text alignment and styling |
| Border | border, border-primary, rounded | Border style and radius |
| Shadow | shadow, shadow-lg | Box shadows |
| Display | d-none, d-sm-block | Responsive display |
Utility API Customization
The Utility API in Sass allows creation of custom utilities:
@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
<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
| State | Classes | Effect |
|---|---|---|
| Valid | is-valid, .valid-feedback | Green input with success message |
| Invalid | is-invalid, .invalid-feedback | Red input with error message |
| Validation upon submission | needs-validation, was-validated | Validate on submit |
Custom Form Controls
| Control | Classes | Description |
|---|---|---|
| Switches | form-check form-switch | Toggle switches |
| Range | form-range | Slider controls |
| File inputs | form-control | File selectors |
| Input groups | input-group | Combined form elements |
| Floating labels | form-floating | Labels that float on focus |
Advanced Grid Techniques
Auto-Layout Columns
<!-- 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
<!-- 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
<!-- 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
<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:
<!-- 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
<!-- 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
<!-- 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
<!-- 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
<!-- 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
<!-- 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
<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
<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
<!-- 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)
// 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
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
// 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
- 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
- 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
- Mobile-First Development
- Start with mobile layouts first
- Use responsive breakpoint utilities strategically
- Test on real devices frequently
- Optimize touch targets (min 44x44px)
- Accessibility Implementation
- Maintain proper heading hierarchy
- Use semantic HTML elements
- Include appropriate ARIA attributes
- Ensure keyboard navigation works
- Test with screen readers
- 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
- Official Documentation
- Learning Resources
- Tools
- 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.
