📚 Introduction to Bootstrap 5.3
What is Bootstrap?
Bootstrap is a powerful, feature-packed front-end toolkit that provides a comprehensive collection of pre-designed HTML, CSS, and JavaScript components. It enables developers to build responsive, mobile-first websites quickly and efficiently without writing extensive custom CSS.
Why Use Bootstrap?
- Rapid Development: Pre-built components save hours of development time
- Responsive by Default: Mobile-first approach ensures your site works on all devices
- Consistency: Uniform design language across your entire application
- Browser Compatibility: Works seamlessly across all modern browsers
- Customizable: Easy to customize with Sass variables and mixins
- Large Community: Extensive documentation and community support
- Accessibility: Built with accessibility best practices in mind
- No jQuery dependency - Pure JavaScript
- Enhanced CSS custom properties (CSS variables)
- Improved color modes (light/dark theme support)
- New utility classes and components
- Better performance and smaller file sizes
Getting Started
Method 1: CDN (Content Delivery Network) - Recommended for Beginners
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap JavaScript Bundle (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
Why use CDN?
CDN delivers Bootstrap files from servers closest to your users, resulting in faster load times. It also leverages browser caching - if users have visited other sites using the same CDN, the files are already cached.
Method 2: NPM (Node Package Manager) - For Advanced Projects
npm install bootstrap@5.3.2
Method 3: Download Source Files
Download from getbootstrap.com and include in your project manually.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap 5.3 Page</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>Hello, Bootstrap!</h1>
<!-- Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
viewport meta tag is crucial for responsive design.
It ensures proper rendering and touch zooming on mobile devices.
Understanding Bootstrap's Naming Convention
Class Naming Pattern
Bootstrap uses a systematic naming convention that makes classes predictable and easy to remember:
{property}-{value} or {property}-{breakpoint}-{value}
| Abbreviation | Meaning | Example |
|---|---|---|
m |
margin | m-3 = margin on all sides |
p |
padding | p-4 = padding on all sides |
t |
top | mt-2 = margin-top |
b |
bottom | pb-3 = padding-bottom |
s |
start (left in LTR) | ms-2 = margin-start |
e |
end (right in LTR) | pe-3 = padding-end |
x |
horizontal (left & right) | mx-auto = margin left & right auto |
y |
vertical (top & bottom) | py-5 = padding top & bottom |
| Breakpoint | Class Infix | Dimensions | Device Type |
|---|---|---|---|
| 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 |
How Breakpoints Work
Bootstrap uses a mobile-first approach. This means:
- Classes without a breakpoint (like
col-6) apply to all screen sizes - Classes with a breakpoint (like
col-md-6) apply from that breakpoint and up - You can combine multiple breakpoints:
col-12 col-md-6 col-lg-4
Bootstrap provides a comprehensive color palette with semantic meaning:
Why Semantic Colors?
- Primary: Main brand color, used for primary actions
- Secondary: Supporting color for less prominent actions
- Success: Indicates successful or positive actions
- Danger: Indicates errors or dangerous actions
- Warning: Indicates caution or important information
- Info: Provides informational messages
- Light/Dark: For contrast and visual hierarchy
🎨 Layout System
What is the Grid System?
Bootstrap's grid system is the foundation of responsive layouts. It uses a 12-column flexible grid that adapts to different screen sizes. Think of it as dividing your page into 12 equal vertical slices that you can combine in various ways.
1. Containers
Understanding Containers
Containers are the most basic layout element in Bootstrap. They provide a means to center and horizontally pad your site's contents. All grid systems must be placed inside a container.
1. Fixed-Width Container (.container)
A responsive fixed-width container that changes its max-width at each breakpoint:
- Extra small (<576px): 100% width
- Small (≥576px): 540px max-width
- Medium (≥768px): 720px max-width
- Large (≥992px): 960px max-width
- Extra large (≥1200px): 1140px max-width
- Extra extra large (≥1400px): 1320px max-width
<div class="container">
<!-- Content here will be centered with responsive max-width -->
<h1>Fixed-Width Container</h1>
<p>This container has a maximum width that changes based on screen size.</p>
</div>
This is a fixed-width container. Resize your browser to see how it adapts!
2. Fluid Container (.container-fluid)
A full-width container that spans 100% of the viewport width at all breakpoints. Perfect for full-width designs or when you want content to stretch across the entire screen.
<div class="container-fluid">
<!-- Content spans the full width of the viewport -->
<h1>Full-Width Container</h1>
<p>This container always takes up 100% of the screen width.</p>
</div>
This is a fluid container. It always spans the full width!
3. Responsive Containers (.container-{breakpoint})
These containers are 100% wide until the specified breakpoint, then they behave like a fixed
container. Available options: container-sm, container-md,
container-lg, container-xl, container-xxl
<div class="container-md">
<!-- 100% wide until medium breakpoint (768px), then fixed width -->
<p>Fluid on mobile, fixed on tablets and up</p>
</div>
When to Use Each Container Type?
- .container: Most common choice for standard websites with centered content
- .container-fluid: Full-width designs, dashboards, or when you want edge-to-edge content
- .container-{breakpoint}: When you want fluid layout on mobile but fixed on larger screens
2. Grid System - Rows and Columns
How the Grid Works
Bootstrap's grid system uses a series of containers, rows, and columns to layout and align content. It's built with flexbox and is fully responsive. Here's how it works:
- Container: Wraps the entire grid and provides proper alignment
- Row: Creates a horizontal group of columns and removes negative margins
- Columns: Your content goes here. Columns are the immediate children of rows
Bootstrap divides each row into 12 equal parts. You can combine these parts to create columns of different widths:
- One column spanning full width = 12 parts
- Two equal columns = 6 parts each
- Three equal columns = 4 parts each
- Four equal columns = 3 parts each
- You can mix: 8 parts + 4 parts, 3 parts + 6 parts + 3 parts, etc.
<div class="container">
<div class="row">
<div class="col">
Column 1 - Equal width
</div>
<div class="col">
Column 2 - Equal width
</div>
<div class="col">
Column 3 - Equal width
</div>
</div>
</div>
What's Happening Here?
When you use .col without a number, Bootstrap automatically divides the
available space equally among all columns. Each column gets the same width, regardless of
content.
Use .col-{number} to specify exactly how many of the 12 parts each column should
occupy. The number can be from 1 to 12.
<div class="container">
<div class="row">
<div class="col-4">
Takes 4/12 = 33.33% width
</div>
<div class="col-8">
Takes 8/12 = 66.67% width
</div>
</div>
</div>
The Power of Responsive Design
This is where Bootstrap truly shines! You can specify different column widths for different
screen sizes using breakpoint prefixes: .col-{breakpoint}-{number}
The mobile-first approach means:
- Start with the smallest screen (mobile)
- Add breakpoints as screens get larger
- Each breakpoint applies to that size and larger (unless overridden)
<div class="container">
<div class="row">
<div class="col-12 col-md-6 col-lg-4">
<!--
Mobile (xs): 100% width (col-12)
Tablet (md): 50% width (col-md-6)
Desktop (lg): 33.33% width (col-lg-4)
-->
Responsive Column 1
</div>
<div class="col-12 col-md-6 col-lg-4">
Responsive Column 2
</div>
<div class="col-12 col-md-12 col-lg-4">
Responsive Column 3
</div>
</div>
</div>
Mobile: 100% | Tablet: 50% | Desktop: 33%
Mobile: 100% | Tablet: 50% | Desktop: 33%
Mobile: 100% | Tablet: 100% | Desktop: 33%
Real-World Example: Product Grid
Imagine an e-commerce site showing products:
- Mobile: 1 product per row (col-12) - easy to see on small screens
- Tablet: 2 products per row (col-md-6) - better use of space
- Desktop: 4 products per row (col-lg-3) - maximum products visible
3. Column Alignment and Positioning
Control how columns align vertically within a row using flexbox alignment classes. These
classes are applied to the .row element.
| Class | Effect | Use Case |
|---|---|---|
.align-items-start |
Aligns columns to the top | When you want content to start from the top |
.align-items-center |
Centers columns vertically | Perfect for centering content in hero sections |
.align-items-end |
Aligns columns to the bottom | When you want content aligned at the bottom |
<div class="container">
<!-- Align all columns to center -->
<div class="row align-items-center" style="min-height: 200px;">
<div class="col">Column 1</div>
<div class="col">Column 2</div>
<div class="col">Column 3</div>
</div>
</div>
Control how columns are distributed horizontally within a row. These classes are also applied
to the .row element.
| Class | Effect |
|---|---|
.justify-content-start |
Columns start from the left (default) |
.justify-content-center |
Columns are centered |
.justify-content-end |
Columns are pushed to the right |
.justify-content-around |
Equal space around each column |
.justify-content-between |
Space between columns, none at edges |
.justify-content-evenly |
Equal space between and around columns |
Move columns to the right using .offset-{number} or
.offset-{breakpoint}-{number} classes. This adds left margin to push the column
over.
<div class="row">
<div class="col-4 offset-4">
<!-- This column is centered (4 columns wide, offset by 4) -->
Centered Column
</div>
</div>
4. Gutters (Spacing Between Columns)
What are Gutters?
Gutters are the padding between columns. By default, Bootstrap adds 1.5rem (24px) of padding between columns. You can customize this spacing using gutter classes.
| Class | Direction | Values |
|---|---|---|
.g-{0-5} |
Both horizontal & vertical | 0, 1, 2, 3, 4, 5 |
.gx-{0-5} |
Horizontal only | 0, 1, 2, 3, 4, 5 |
.gy-{0-5} |
Vertical only | 0, 1, 2, 3, 4, 5 |
<!-- No gutters -->
<div class="row g-0">
<div class="col">Column 1</div>
<div class="col">Column 2</div>
</div>
<!-- Large gutters -->
<div class="row g-5">
<div class="col">Column 1</div>
<div class="col">Column 2</div>
</div>
🛠️ Utility Classes
What are Utility Classes?
Utility classes are single-purpose classes that apply a specific style. They're the building blocks of rapid development, allowing you to style elements without writing custom CSS. Think of them as CSS shortcuts!
Spacing Utilities
Understanding Spacing
Spacing utilities control margin and padding. The format is:
{property}{sides}-{size} or {property}{sides}-{breakpoint}-{size}
Property: m (margin) or p (padding)
Sides: t (top), b (bottom), s
(start/left), e (end/right), x (horizontal), y
(vertical), or blank (all sides)
Size: 0, 1, 2, 3, 4, 5, or auto
| Size | Value | Pixels (approx) |
|---|---|---|
| 0 | 0 | 0px |
| 1 | 0.25rem | 4px |
| 2 | 0.5rem | 8px |
| 3 | 1rem | 16px |
| 4 | 1.5rem | 24px |
| 5 | 3rem | 48px |
Common Spacing Examples
<!-- Margin examples -->
<div class="m-3">Margin on all sides (16px)</div>
<div class="mt-5">Margin top only (48px)</div>
<div class="mx-auto">Horizontal margin auto (centers block element)</div>
<div class="my-4">Vertical margin (24px top and bottom)</div>
<!-- Padding examples -->
<div class="p-4">Padding on all sides (24px)</div>
<div class="px-3">Horizontal padding (16px left and right)</div>
<div class="py-2">Vertical padding (8px top and bottom)</div>
Display Utilities
Control the display property of elements. Format: .d-{value} or
.d-{breakpoint}-{value}
Values: none, inline, inline-block, block, grid, table, table-cell, table-row, flex, inline-flex
Display Examples
<!-- Hide element -->
<div class="d-none">Hidden on all screens</div>
<!-- Show only on large screens -->
<div class="d-none d-lg-block">Visible only on large screens and up</div>
<!-- Hide on mobile, show on tablet and up -->
<div class="d-none d-md-block">Hidden on mobile, visible on tablet+</div>
<!-- Flexbox -->
<div class="d-flex">Flex container</div>
Flexbox Utilities
Flexbox Made Easy
Bootstrap provides comprehensive flexbox utilities. First, make an element a flex container
with .d-flex, then use these utilities to control layout.
<div class="d-flex flex-row">Horizontal (default)</div>
<div class="d-flex flex-row-reverse">Horizontal reversed</div>
<div class="d-flex flex-column">Vertical</div>
<div class="d-flex flex-column-reverse">Vertical reversed</div>
<div class="d-flex justify-content-start">Items at start</div>
<div class="d-flex justify-content-center">Items centered</div>
<div class="d-flex justify-content-end">Items at end</div>
<div class="d-flex justify-content-between">Space between items</div>
<div class="d-flex justify-content-around">Space around items</div>
<div class="d-flex justify-content-evenly">Equal space</div>
<div class="d-flex align-items-start">Items at top</div>
<div class="d-flex align-items-center">Items centered</div>
<div class="d-flex align-items-end">Items at bottom</div>
<div class="d-flex align-items-stretch">Items stretched</div>
Text Utilities
<p class="text-start">Left aligned text</p>
<p class="text-center">Center aligned text</p>
<p class="text-end">Right aligned text</p>
<p class="text-lowercase">LOWERCASED TEXT</p>
<p class="text-uppercase">uppercased text</p>
<p class="text-capitalize">capitalized text</p>
<p class="fw-bold">Bold text</p>
<p class="fw-bolder">Bolder text</p>
<p class="fw-semibold">Semibold text</p>
<p class="fw-normal">Normal weight text</p>
<p class="fw-light">Light weight text</p>
<p class="fw-lighter">Lighter weight text</p>
<p class="fst-italic">Italic text</p>
<p class="fst-normal">Normal style text</p>
<p class="fs-1">Font size 1 (largest)</p>
<p class="fs-2">Font size 2</p>
<p class="fs-3">Font size 3</p>
<p class="fs-4">Font size 4</p>
<p class="fs-5">Font size 5</p>
<p class="fs-6">Font size 6 (smallest)</p>
Color Utilities
Primary text
Secondary text
Success text
Danger text
Warning text
Info text
Light text
Dark text
Muted text
🧩 Bootstrap Components
What are Components?
Components are pre-built, reusable UI elements that combine HTML, CSS, and sometimes JavaScript. They provide consistent, professional-looking interfaces with minimal effort.
Buttons
Buttons are one of the most used components. Bootstrap provides extensive button styling with semantic colors, sizes, and states.
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
Cards
Understanding Cards
Cards are flexible content containers with multiple variants and options. They can include headers, footers, images, and various content types. Perfect for displaying products, articles, profiles, and more.
Card with Header
Cards can have headers and footers for additional context.
<div class="card">
<img src="image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Card content goes here.</p>
<a href="#" class="btn btn-primary">Button</a>
</div>
</div>
Alerts
Alerts provide contextual feedback messages for user actions. They're perfect for success messages, warnings, errors, and informational notices.
Badges
Badges are small count and labeling components. They scale to match the size of their parent element.
Heading New
Heading Featured
Pill BadgeAccordion
Understanding Accordions
Accordions are vertically collapsing elements perfect for FAQs, menus, and content organization. They save space by showing only one section at a time.
<div class="accordion" id="accordionExample">
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button" type="button"
data-bs-toggle="collapse" data-bs-target="#collapseOne">
Accordion Item #1
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse show"
data-bs-parent="#accordionExample">
<div class="accordion-body">
Content for first item
</div>
</div>
</div>
</div>
Accordion Key Classes
.accordion- Container for all items.accordion-item- Individual accordion section.accordion-header- Header containing the button.accordion-button- Clickable button.accordion-collapse- Collapsible content wrapper.accordion-body- Actual content.show- Makes item expanded by default.collapsed- Makes button appear collapsed
Carousel
Image Sliders Made Easy
Carousels are slideshow components for cycling through images, text, or custom content. Perfect for hero sections, product showcases, and testimonials.
Tabs and Pills
Tabbed Navigation
Tabs organize content into separate views that users can switch between. Perfect for settings pages, product details, and multi-step forms.
<!-- Tab Navigation -->
<ul class="nav nav-tabs" id="myTab">
<li class="nav-item">
<button class="nav-link active" data-bs-toggle="tab"
data-bs-target="#home">Home</button>
</li>
<li class="nav-item">
<button class="nav-link" data-bs-toggle="tab"
data-bs-target="#profile">Profile</button>
</li>
</ul>
<!-- Tab Content -->
<div class="tab-content">
<div class="tab-pane fade show active" id="home">
Home content
</div>
<div class="tab-pane fade" id="profile">
Profile content
</div>
</div>
Toasts
Lightweight Notifications
Toasts are lightweight notifications designed to mimic push notifications. They're perfect for success messages, updates, and non-intrusive alerts.
<!-- Toast Container -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div class="toast" role="alert">
<div class="toast-header">
<strong class="me-auto">Notification</strong>
<small>Just now</small>
<button type="button" class="btn-close"
data-bs-dismiss="toast"></button>
</div>
<div class="toast-body">
Your message here
</div>
</div>
</div>
<!-- JavaScript to show toast -->
<script>
const toastEl = document.querySelector('.toast');
const toast = new bootstrap.Toast(toastEl);
toast.show();
</script>
Offcanvas
Sidebar Panels
Offcanvas components are hidden sidebars that slide in from the edge of the viewport. Perfect for mobile menus, filters, shopping carts, and settings panels.
Offcanvas Title
This is offcanvas content. It can contain any HTML elements!
- Navigation links
- Forms
- Filters
- Shopping cart
<!-- Trigger Button -->
<button data-bs-toggle="offcanvas" data-bs-target="#offcanvasExample">
Open Sidebar
</button>
<!-- Offcanvas -->
<div class="offcanvas offcanvas-start" id="offcanvasExample">
<div class="offcanvas-header">
<h5 class="offcanvas-title">Title</h5>
<button type="button" class="btn-close"
data-bs-dismiss="offcanvas"></button>
</div>
<div class="offcanvas-body">
Content here
</div>
</div>
Offcanvas Positions
.offcanvas-start- Slides from left.offcanvas-end- Slides from right.offcanvas-top- Slides from top.offcanvas-bottom- Slides from bottom
Progress Bars
Visual Progress Indicators
Progress bars show the completion status of tasks, uploads, downloads, or multi-step processes.
Spinners
Loading Indicators
Spinners indicate loading states. They're lightweight, built with HTML and CSS, and require no JavaScript.
Navbar
Building Navigation
Navbars are responsive navigation headers. They collapse on mobile and expand on larger screens. Essential for any website!
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
Navbar Key Classes Explained
.navbar- Base navbar class.navbar-expand-{breakpoint}- When to expand (lg, md, etc.).navbar-darkor.navbar-light- Color scheme.navbar-toggler- Mobile menu button.navbar-collapse- Collapsible content.navbar-nav- Navigation links container.nav-item- Individual navigation item.nav-link- Navigation link styling
Modal
Understanding Modals
Modals are dialog boxes that appear on top of the page content. Perfect for forms, confirmations, alerts, or any content that needs user attention.
<!-- Button trigger -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#myModal">
Open Modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="btn-close"
data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
Modal content goes here...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
📝 Forms
Bootstrap Form System
Bootstrap provides comprehensive form styling that's consistent across browsers and devices. Forms are essential for user input, and Bootstrap makes them beautiful and functional.
Form Controls
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email"
placeholder="name@example.com">
<div class="form-text">Help text goes here</div>
</div>
Form Classes Explained
.form-label- Styles the label element.form-control- Styles input, textarea, and select elements.form-text- Adds help text below inputs.mb-3- Adds bottom margin for spacing
Input groups allow you to add text, buttons, or button groups on either side of textual inputs.
Floating labels are a modern design pattern where the label floats above the input when focused or filled.
Bootstrap provides validation styles for success, warning, and error states.
🔧 Bootstrap Data Attributes - Complete Guide
What are Data Attributes?
Data attributes are HTML5 attributes that start with data-. Bootstrap uses them
extensively to add JavaScript functionality without writing any JavaScript code. They're the
magic that makes Bootstrap components interactive!
Format: data-bs-{functionality}="{value}"
Why "bs"? The "bs" prefix stands for "Bootstrap" and prevents conflicts with other libraries.
Core Data Attributes
Purpose
Activates a Bootstrap JavaScript component. This is the most commonly used data attribute.
How it works: When you click an element with data-bs-toggle,
Bootstrap automatically initializes and shows the specified component.
| Value | Component | What It Does |
|---|---|---|
modal |
Modal | Opens a modal dialog |
dropdown |
Dropdown | Toggles dropdown menu |
collapse |
Collapse | Expands/collapses content |
offcanvas |
Offcanvas | Opens sidebar panel |
tab |
Tab | Switches between tabs |
pill |
Pill | Switches between pills |
tooltip |
Tooltip | Shows tooltip on hover |
popover |
Popover | Shows popover on click |
button |
Button | Toggles button state |
Examples of data-bs-toggle
<!-- Modal Toggle -->
<button data-bs-toggle="modal" data-bs-target="#myModal">
Open Modal
</button>
<!-- Dropdown Toggle -->
<button data-bs-toggle="dropdown">
Dropdown Menu
</button>
<!-- Collapse Toggle -->
<button data-bs-toggle="collapse" data-bs-target="#collapseContent">
Toggle Content
</button>
<!-- Tooltip Toggle -->
<button data-bs-toggle="tooltip" data-bs-title="Helpful tip!">
Hover me
</button>
Purpose
Specifies which element to target/control. Works with CSS selectors (ID or class).
How it works: Points to the element that should be affected by the toggle action.
Format: data-bs-target="#elementId" or
data-bs-target=".className"
Detailed Examples
<!-- Target by ID (most common) -->
<button data-bs-toggle="modal" data-bs-target="#loginModal">
Login
</button>
<div class="modal" id="loginModal">
<!-- Modal content -->
</div>
<!-- Target by Class (multiple elements) -->
<button data-bs-toggle="collapse" data-bs-target=".multi-collapse">
Toggle All
</button>
<div class="collapse multi-collapse">Content 1</div>
<div class="collapse multi-collapse">Content 2</div>
<!-- Target multiple elements -->
<button data-bs-toggle="collapse" data-bs-target="#item1, #item2">
Toggle Multiple
</button>
Why Use data-bs-target Instead of href?
- Semantic Clarity: Makes it clear this is a JavaScript action, not a link
- Works on Any Element: Can be used on buttons, divs, spans, not just links
- Better Accessibility: Screen readers understand the purpose better
- No Page Jump: Prevents unwanted scrolling that can happen with href="#id"
Purpose
Closes/dismisses a component. Essential for close buttons in modals, alerts, toasts, and offcanvas.
How it works: When clicked, automatically closes the parent component without needing JavaScript.
| Value | Closes | Common Use |
|---|---|---|
modal |
Modal dialog | Close button in modal header/footer |
alert |
Alert message | X button in dismissible alerts |
toast |
Toast notification | Close button in toast |
offcanvas |
Offcanvas panel | Close button in offcanvas |
Dismiss Examples
<!-- Modal Close Button -->
<div class="modal">
<div class="modal-header">
<h5>Modal Title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
</div>
<!-- Dismissible Alert -->
<div class="alert alert-warning alert-dismissible">
Warning message!
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<!-- Toast Close -->
<div class="toast">
<div class="toast-header">
<strong>Notification</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast"></button>
</div>
</div>
Purpose
Controls carousel navigation. Tells the carousel which direction to slide or which slide to show.
| Value | Action | Use Case |
|---|---|---|
prev |
Go to previous slide | Previous button |
next |
Go to next slide | Next button |
Carousel Navigation
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<div class="carousel-item active">Slide 1</div>
<div class="carousel-item">Slide 2</div>
</div>
<!-- Previous Button -->
<button class="carousel-control-prev" data-bs-target="#myCarousel"
data-bs-slide="prev">
<span class="carousel-control-prev-icon"></span>
</button>
<!-- Next Button -->
<button class="carousel-control-next" data-bs-target="#myCarousel"
data-bs-slide="next">
<span class="carousel-control-next-icon"></span>
</button>
</div>
Purpose
Jumps to a specific slide in a carousel by index (starting from 0).
How it works: Creates indicator dots or numbered buttons that jump directly to specific slides.
Carousel Indicators
<div id="carouselExample" class="carousel slide">
<!-- Indicators -->
<div class="carousel-indicators">
<button data-bs-target="#carouselExample" data-bs-slide-to="0"
class="active"></button>
<button data-bs-target="#carouselExample" data-bs-slide-to="1"></button>
<button data-bs-target="#carouselExample" data-bs-slide-to="2"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active">Slide 1</div>
<div class="carousel-item">Slide 2</div>
<div class="carousel-item">Slide 3</div>
</div>
</div>
Purpose
Controls carousel auto-play behavior.
| Value | Behavior |
|---|---|
carousel |
Auto-plays immediately on page load |
true |
Auto-plays after first user interaction |
| Not set | Manual control only (no auto-play) |
Auto-Play Examples
<!-- Auto-play immediately -->
<div class="carousel slide" data-bs-ride="carousel">
<!-- Starts sliding automatically -->
</div>
<!-- Auto-play after interaction -->
<div class="carousel slide" data-bs-ride="true">
<!-- Starts after user clicks next/prev -->
</div>
<!-- Manual only -->
<div class="carousel slide">
<!-- Only moves when user clicks controls -->
</div>
Purpose
Sets the delay (in milliseconds) between automatically cycling carousel items.
Default: 5000ms (5 seconds)
Special value: false disables auto-cycling for that slide
Custom Timing Examples
<!-- Global interval on carousel -->
<div class="carousel slide" data-bs-ride="carousel" data-bs-interval="3000">
<!-- All slides show for 3 seconds -->
</div>
<!-- Per-slide intervals -->
<div class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active" data-bs-interval="10000">
<!-- This slide shows for 10 seconds -->
</div>
<div class="carousel-item" data-bs-interval="2000">
<!-- This slide shows for 2 seconds -->
</div>
<div class="carousel-item" data-bs-interval="false">
<!-- This slide doesn't auto-advance -->
</div>
</div>
</div>
Purpose
Creates accordion behavior by ensuring only one collapse element is open at a time within a parent container.
How it works: When you open one item, all other items with the same parent automatically close.
Accordion Example
<div class="accordion" id="accordionExample">
<!-- Item 1 -->
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button" data-bs-toggle="collapse"
data-bs-target="#collapseOne">
Item 1
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse show"
data-bs-parent="#accordionExample">
<div class="accordion-body">Content 1</div>
</div>
</div>
<!-- Item 2 -->
<div class="accordion-item">
<h2 class="accordion-header">
<button class="accordion-button collapsed" data-bs-toggle="collapse"
data-bs-target="#collapseTwo">
Item 2
</button>
</h2>
<div id="collapseTwo" class="accordion-collapse collapse"
data-bs-parent="#accordionExample">
<div class="accordion-body">Content 2</div>
</div>
</div>
</div>
<!-- Without data-bs-parent: Multiple items can be open -->
<!-- With data-bs-parent: Only one item open at a time -->
Purpose (NEW in Bootstrap 5.3)
Enables color mode switching between light and dark themes. This is a game-changer for modern web design!
Values: light, dark, or auto
Theme Switching Examples
<!-- Apply to entire page -->
<html data-bs-theme="dark">
<!-- Everything uses dark theme -->
</html>
<!-- Apply to specific section -->
<div data-bs-theme="dark">
<!-- Only this section is dark -->
<div class="card">Dark themed card</div>
</div>
<!-- Auto theme (follows system preference) -->
<html data-bs-theme="auto">
<!-- Matches user's OS theme -->
</html>
<!-- Dynamic theme switching with JavaScript -->
<button onclick="document.documentElement.setAttribute('data-bs-theme', 'dark')">
Dark Mode
</button>
<button onclick="document.documentElement.setAttribute('data-bs-theme', 'light')">
Light Mode
</button>
Light Theme
Dark Theme
Purpose
Controls where tooltips and popovers appear relative to their trigger element.
Values: top, bottom, left,
right, auto
Placement Examples
<!-- Tooltip on top -->
<button data-bs-toggle="tooltip" data-bs-placement="top"
data-bs-title="Tooltip on top">
Hover me
</button>
<!-- Popover on right -->
<button data-bs-toggle="popover" data-bs-placement="right"
data-bs-title="Title" data-bs-content="Content here">
Click me
</button>
<!-- Auto placement (Bootstrap chooses best position) -->
<button data-bs-toggle="tooltip" data-bs-placement="auto"
data-bs-title="Smart positioning">
Smart tooltip
</button>
✨ Best Practices & Tips
Always design for mobile first, then add breakpoints for larger screens. This ensures your site works on all devices.
Use appropriate HTML elements (nav, header, footer, article, section) along with Bootstrap classes for better accessibility and SEO.
Instead of modifying Bootstrap's CSS, use custom classes or CSS variables to customize your design.
Before writing custom CSS, check if Bootstrap has a utility class that does what you need.
Always test your layouts on different screen sizes using browser dev tools or real devices.
Use proper ARIA labels, semantic HTML, and ensure keyboard navigation works correctly.
Only include the Bootstrap components you need. Consider using a custom build or tree-shaking with a bundler.
🎯 Advanced Data Attributes
Purpose
Sets the title/content for tooltips. Replaces the old title attribute for better
control.
<button data-bs-toggle="tooltip" data-bs-title="This is the tooltip text">
Hover for tooltip
</button>
Purpose
Sets the body content for popovers (used with data-bs-title for the header).
<button data-bs-toggle="popover"
data-bs-title="Popover Title"
data-bs-content="This is the popover body content with more details.">
Click for popover
</button>
Purpose
Defines how tooltips and popovers are triggered.
Values: click, hover, focus,
manual, or combinations like hover focus
<!-- Click to show/hide -->
<button data-bs-toggle="popover" data-bs-trigger="click">Click me</button>
<!-- Show on hover -->
<button data-bs-toggle="tooltip" data-bs-trigger="hover">Hover me</button>
<!-- Show on focus -->
<input data-bs-toggle="tooltip" data-bs-trigger="focus"
data-bs-title="Enter your name">
<!-- Multiple triggers -->
<button data-bs-toggle="popover" data-bs-trigger="hover focus">
Hover or focus
</button>
Purpose
Sets delay (in milliseconds) before showing/hiding tooltips and popovers.
Format: Single number (same for show/hide) or object
{"show":500,"hide":100}
<!-- 500ms delay for both show and hide -->
<button data-bs-toggle="tooltip" data-bs-delay="500">Delayed tooltip</button>
<!-- Different delays for show and hide -->
<button data-bs-toggle="tooltip"
data-bs-delay='{"show":1000,"hide":200}'>
Custom delays
</button>
Purpose
Enables/disables CSS fade animation for components.
Values: true (default) or false
<!-- With animation (default) -->
<button data-bs-toggle="modal" data-bs-target="#modal1" data-bs-animation="true">
Animated modal
</button>
<!-- Without animation (instant) -->
<button data-bs-toggle="modal" data-bs-target="#modal2" data-bs-animation="false">
Instant modal
</button>
Purpose
Controls modal and offcanvas backdrop behavior.
Values:
true(default) - Shows backdrop, closes on clickfalse- No backdropstatic- Shows backdrop, doesn't close on click
<!-- Standard modal (closes on backdrop click) -->
<div class="modal" data-bs-backdrop="true">...</div>
<!-- Modal without backdrop -->
<div class="modal" data-bs-backdrop="false">...</div>
<!-- Modal that doesn't close on backdrop click -->
<div class="modal" data-bs-backdrop="static">...</div>
Purpose
Controls whether pressing ESC key closes modals and offcanvas.
Values: true (default) or false
<!-- Can close with ESC key -->
<div class="modal" data-bs-keyboard="true">...</div>
<!-- Cannot close with ESC key -->
<div class="modal" data-bs-keyboard="false">...</div>
Purpose
Controls whether modal automatically receives focus when opened.
Values: true (default) or false
Purpose
Allows body scrolling while offcanvas is open.
Values: true or false (default)
<!-- Allow scrolling behind offcanvas -->
<div class="offcanvas" data-bs-scroll="true">...</div>
Purpose
Controls dropdown auto-close behavior.
Values:
true(default) - Closes on outside clickfalse- Never auto-closesinside- Closes only on inside clickoutside- Closes only on outside click
<!-- Standard dropdown -->
<div class="dropdown" data-bs-auto-close="true">...</div>
<!-- Stays open (useful for forms in dropdowns) -->
<div class="dropdown" data-bs-auto-close="false">...</div>
<!-- Closes only when clicking inside -->
<div class="dropdown" data-bs-auto-close="inside">...</div>
Purpose
Sets offset distance for dropdowns, tooltips, and popovers.
Format: [horizontal, vertical] in pixels
<!-- Offset dropdown by 10px horizontally, 20px vertically -->
<button data-bs-toggle="dropdown" data-bs-offset="10,20">
Dropdown
</button>
Purpose
Sets reference element for dropdown positioning.
Values: toggle (default), parent, or CSS selector
Purpose
Controls dropdown display mode.
Values: dynamic (default) or static
Purpose
Sets overflow constraint boundary for dropdowns and popovers.
Values: clippingParents (default), viewport, or
CSS selector
Purpose
Specifies where to append tooltip/popover element in the DOM.
Values: false (default), body, or CSS selector
<!-- Append to body (useful for overflow issues) -->
<button data-bs-toggle="tooltip" data-bs-container="body">
Tooltip
</button>
Purpose
Allows HTML content in tooltips and popovers.
Values: true or false (default)
⚠️ Security Warning: Only use with trusted content to prevent XSS attacks!
<button data-bs-toggle="tooltip" data-bs-html="true"
data-bs-title="<strong>Bold</strong> and <em>italic</em>">
HTML tooltip
</button>
Purpose
Enables/disables HTML sanitization for security.
Values: true (default) or false
Purpose
Enables/disables touch swipe gestures on carousels.
Values: true (default) or false
<!-- Disable swipe on mobile -->
<div class="carousel slide" data-bs-touch="false">...</div>
Purpose
Controls carousel pause behavior on hover.
Values: hover (default) or false
<!-- Pause on hover -->
<div class="carousel slide" data-bs-pause="hover">...</div>
<!-- Never pause -->
<div class="carousel slide" data-bs-pause="false">...</div>
Purpose
Controls whether carousel cycles continuously or stops at the last slide.
Values: true (default) or false
<!-- Continuous cycling -->
<div class="carousel slide" data-bs-wrap="true">...</div>
<!-- Stop at last slide -->
<div class="carousel slide" data-bs-wrap="false">...</div>
You can combine multiple data attributes for powerful, customized behavior:
<div class="modal fade" id="customModal"
data-bs-backdrop="static"
data-bs-keyboard="false"
data-bs-focus="true">
<!-- This modal:
- Cannot be closed by clicking backdrop
- Cannot be closed with ESC key
- Automatically receives focus
-->
</div>
Why So Many Data Attributes?
- No JavaScript Required: Configure complex behaviors without writing code
- Declarative: Behavior is clear from reading the HTML
- Maintainable: Easy to modify behavior by changing attributes
- Flexible: Mix and match for custom functionality
- Accessible: Works with Bootstrap's built-in accessibility features
⚡ JavaScript API - Advanced Control
When to Use JavaScript API
While data attributes handle most use cases, the JavaScript API gives you programmatic control for:
- Dynamic component creation
- Responding to events
- Complex interactions
- Integration with frameworks (React, Vue, Angular)
Initializing Components
// Get element
const myModalEl = document.getElementById('myModal');
// Create instance
const modal = new bootstrap.Modal(myModalEl, {
backdrop: 'static',
keyboard: false
});
// Show modal
modal.show();
// Get existing instance (if already initialized)
const modal = bootstrap.Modal.getInstance(myModalEl);
// Or get/create instance
const modal = bootstrap.Modal.getOrCreateInstance(myModalEl);
Component Methods
const modal = new bootstrap.Modal('#myModal');
// Show modal
modal.show();
// Hide modal
modal.hide();
// Toggle modal
modal.toggle();
// Update modal (refresh positioning)
modal.handleUpdate();
// Destroy modal instance
modal.dispose();
const dropdown = new bootstrap.Dropdown('#myDropdown');
dropdown.show(); // Show dropdown
dropdown.hide(); // Hide dropdown
dropdown.toggle(); // Toggle dropdown
dropdown.update(); // Update position
dropdown.dispose(); // Destroy instance
const collapse = new bootstrap.Collapse('#myCollapse');
collapse.show(); // Expand content
collapse.hide(); // Collapse content
collapse.toggle(); // Toggle state
collapse.dispose(); // Destroy instance
const carousel = new bootstrap.Carousel('#myCarousel');
carousel.cycle(); // Start cycling
carousel.pause(); // Pause cycling
carousel.prev(); // Previous slide
carousel.next(); // Next slide
carousel.nextWhenVisible(); // Next when visible
carousel.to(2); // Go to slide index 2
carousel.dispose(); // Destroy instance
Component Events
Understanding Bootstrap Events
Bootstrap components fire events at different stages of their lifecycle. You can listen to these events to run custom code.
Event Naming Pattern: {action}.bs.{component}
const myModal = document.getElementById('myModal');
// Before modal shows
myModal.addEventListener('show.bs.modal', function (event) {
console.log('Modal is about to show');
// You can prevent showing with event.preventDefault()
});
// After modal is shown
myModal.addEventListener('shown.bs.modal', function (event) {
console.log('Modal is now visible');
// Focus on input, start animation, etc.
});
// Before modal hides
myModal.addEventListener('hide.bs.modal', function (event) {
console.log('Modal is about to hide');
});
// After modal is hidden
myModal.addEventListener('hidden.bs.modal', function (event) {
console.log('Modal is now hidden');
// Clean up, reset form, etc.
});
// When modal backdrop is clicked
myModal.addEventListener('hidePrevented.bs.modal', function (event) {
console.log('Hide was prevented (static backdrop)');
});
const myCarousel = document.getElementById('myCarousel');
// Before slide transition
myCarousel.addEventListener('slide.bs.carousel', function (event) {
console.log('Sliding from', event.from, 'to', event.to);
console.log('Direction:', event.direction); // 'left' or 'right'
});
// After slide transition
myCarousel.addEventListener('slid.bs.carousel', function (event) {
console.log('Slide complete');
console.log('Active index:', event.to);
});
const myCollapse = document.getElementById('myCollapse');
myCollapse.addEventListener('show.bs.collapse', function () {
console.log('Starting to expand');
});
myCollapse.addEventListener('shown.bs.collapse', function () {
console.log('Fully expanded');
});
myCollapse.addEventListener('hide.bs.collapse', function () {
console.log('Starting to collapse');
});
myCollapse.addEventListener('hidden.bs.collapse', function () {
console.log('Fully collapsed');
});
const myDropdown = document.getElementById('myDropdown');
myDropdown.addEventListener('show.bs.dropdown', function () {
console.log('Dropdown opening');
});
myDropdown.addEventListener('shown.bs.dropdown', function () {
console.log('Dropdown opened');
});
myDropdown.addEventListener('hide.bs.dropdown', function () {
console.log('Dropdown closing');
});
myDropdown.addEventListener('hidden.bs.dropdown', function () {
console.log('Dropdown closed');
});
Practical Example: Form Validation on Modal
const myModal = document.getElementById('myModal');
const myForm = myModal.querySelector('form');
// Validate when modal is about to hide
myModal.addEventListener('hide.bs.modal', function (event) {
if (!myForm.checkValidity()) {
event.preventDefault(); // Prevent closing
alert('Please fill out all required fields');
}
});
// Reset form when modal is hidden
myModal.addEventListener('hidden.bs.modal', function () {
myForm.reset();
});
Practical Example: Auto-pause Video in Carousel
const carousel = document.getElementById('myCarousel');
carousel.addEventListener('slide.bs.carousel', function (event) {
// Pause video in current slide
const currentSlide = event.relatedTarget;
const video = currentSlide.querySelector('video');
if (video) {
video.pause();
}
});
📚 Additional Resources
Official Documentation
The official Bootstrap documentation is comprehensive and always up-to-date.
Visit DocsContinue Learning
- Practice by building real projects
- Explore Bootstrap themes and templates
- Learn Sass to customize Bootstrap deeply
- Join the Bootstrap community
- Stay updated with new releases