Skip to main content

Complete Bootstrap 5.3 Guide

Master the world's most popular front-end framework with comprehensive explanations, detailed examples, and best practices

Latest Version 5.3 Comprehensive Beginner to Advanced 100+ Examples Free Resource

📚 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
Bootstrap 5.3 Key Features:
  • 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

Installation Methods

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.

Basic HTML Template
<!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>
Important: The 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}

Common Abbreviations
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 System
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
Color System

Bootstrap provides a comprehensive color palette with semantic meaning:

Theme Colors
Primary (#0d6efd)
Secondary (#6c757d)
Success (#198754)
Danger (#dc3545)
Warning (#ffc107)
Info (#0dcaf0)
Light (#f8f9fa)
Dark (#212529)
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.

Container Types

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>
Live Example: Fixed Container

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>
Live Example: Fluid Container

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:

  1. Container: Wraps the entire grid and provides proper alignment
  2. Row: Creates a horizontal group of columns and removes negative margins
  3. Columns: Your content goes here. Columns are the immediate children of rows
Understanding the 12-Column System

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.
Basic Row and Column Structure
<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>
Live Example: Equal Width Columns
Column 1
Column 2
Column 3
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.

Fixed-Width Columns

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>
Live Example: Fixed Width Columns
col-4 (33.33%)
col-8 (66.67%)
col-3
col-6
col-3
Responsive Columns
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>
Live Example: Responsive Columns (Resize browser to see changes)
Column 1
Mobile: 100% | Tablet: 50% | Desktop: 33%
Column 2
Mobile: 100% | Tablet: 50% | Desktop: 33%
Column 3
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

Vertical Alignment

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>
Live Example: Vertical Alignment
Start
Start
Start
Center
Center
Center
End
End
End
Horizontal Alignment

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
Column Offsetting

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.

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.

Flex Direction
<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>
Justify Content (Main Axis)
<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>
Align Items (Cross Axis)
<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

Text Alignment
<p class="text-start">Left aligned text</p>
<p class="text-center">Center aligned text</p>
<p class="text-end">Right aligned text</p>
Text Transform
<p class="text-lowercase">LOWERCASED TEXT</p>
<p class="text-uppercase">uppercased text</p>
<p class="text-capitalize">capitalized text</p>
Font Weight and Style
<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>
Font Size
<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

Text Colors

Primary text

Secondary text

Success text

Danger text

Warning text

Info text

Light text

Dark text

Muted text

Background Colors
Primary background
Secondary background
Success background
Danger background
Warning background
Info background
Light background
Dark background

🧩 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 Variants
<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>
Outline Buttons
Button Sizes

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 image
Card Title

This is a basic card with an image, title, text, and button.

Learn More
Featured
Card with Header

Cards can have headers and footers for additional context.

Colored Card

Cards can have background colors using utility classes.

Action
<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 Badge

Accordion

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.

Bootstrap is a powerful front-end framework for building responsive websites quickly.

Bootstrap provides pre-built components, responsive grid system, and consistent design patterns.

Yes! Bootstrap is completely free and open-source under the MIT license.
<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.

Home Content - This is the home tab content.
Profile Content - This is the profile tab content.
Contact Content - This is the contact tab content.
<!-- 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.

25%
50%
75%
Loading...

Spinners

Loading Indicators

Spinners indicate loading states. They're lightweight, built with HTML and CSS, and require no JavaScript.

Loading...

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-dark or .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

Text Inputs
We'll never share your email with anyone else.
<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
Select Dropdowns
Checkboxes and Radios
Switches
Range Slider
Input Groups

Input groups allow you to add text, buttons, or button groups on either side of textual inputs.

@
@example.com
$ .00
Floating Labels

Floating labels are a modern design pattern where the label floats above the input when focused or filled.

Form Validation

Bootstrap provides validation styles for success, warning, and error states.

Looks good!
Please provide a valid value.
Complete Form Example

🔧 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

1. data-bs-toggle
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>
2. data-bs-target
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"
3. data-bs-dismiss
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>
4. data-bs-slide
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>
5. data-bs-slide-to
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>
6. data-bs-ride
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>
7. data-bs-interval
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>
8. data-bs-parent
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 -->
9. data-bs-theme
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>
Live Theme Demo
Light Theme
Info alert
Dark Theme
Info alert
10. data-bs-placement
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

1. Mobile-First Approach

Always design for mobile first, then add breakpoints for larger screens. This ensures your site works on all devices.

2. Use Semantic HTML

Use appropriate HTML elements (nav, header, footer, article, section) along with Bootstrap classes for better accessibility and SEO.

3. Don't Override Core Bootstrap

Instead of modifying Bootstrap's CSS, use custom classes or CSS variables to customize your design.

4. Leverage Utility Classes

Before writing custom CSS, check if Bootstrap has a utility class that does what you need.

5. Test Responsiveness

Always test your layouts on different screen sizes using browser dev tools or real devices.

6. Accessibility Matters

Use proper ARIA labels, semantic HTML, and ensure keyboard navigation works correctly.

7. Performance Optimization

Only include the Bootstrap components you need. Consider using a custom build or tree-shaking with a bundler.

🎯 Advanced Data Attributes

11. data-bs-title
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>
12. data-bs-content
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>
13. data-bs-trigger
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>
14. data-bs-delay
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>
15. data-bs-animation
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>
16. data-bs-backdrop
Purpose

Controls modal and offcanvas backdrop behavior.

Values:

  • true (default) - Shows backdrop, closes on click
  • false - No backdrop
  • static - 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>
17. data-bs-keyboard
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>
18. data-bs-focus
Purpose

Controls whether modal automatically receives focus when opened.

Values: true (default) or false

19. data-bs-scroll
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>
20. data-bs-auto-close
Purpose

Controls dropdown auto-close behavior.

Values:

  • true (default) - Closes on outside click
  • false - Never auto-closes
  • inside - Closes only on inside click
  • outside - 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>
21. data-bs-offset
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>
22. data-bs-reference
Purpose

Sets reference element for dropdown positioning.

Values: toggle (default), parent, or CSS selector

23. data-bs-display
Purpose

Controls dropdown display mode.

Values: dynamic (default) or static

24. data-bs-boundary
Purpose

Sets overflow constraint boundary for dropdowns and popovers.

Values: clippingParents (default), viewport, or CSS selector

25. data-bs-container
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>
26. data-bs-html
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>
27. data-bs-sanitize
Purpose

Enables/disables HTML sanitization for security.

Values: true (default) or false

28. data-bs-touch
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>
29. data-bs-pause
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>
30. data-bs-wrap
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>
💡 Pro Tip: Combining Data Attributes

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

Method 1: Constructor
// Get element
const myModalEl = document.getElementById('myModal');

// Create instance
const modal = new bootstrap.Modal(myModalEl, {
    backdrop: 'static',
    keyboard: false
});

// Show modal
modal.show();
Method 2: getInstance
// Get existing instance (if already initialized)
const modal = bootstrap.Modal.getInstance(myModalEl);

// Or get/create instance
const modal = bootstrap.Modal.getOrCreateInstance(myModalEl);

Component Methods

Modal 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();
Dropdown Methods
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
Collapse Methods
const collapse = new bootstrap.Collapse('#myCollapse');

collapse.show();    // Expand content
collapse.hide();    // Collapse content
collapse.toggle();  // Toggle state
collapse.dispose(); // Destroy instance
Carousel Methods
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}

Modal Events
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)');
});
Carousel Events
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);
});
Collapse Events
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');
});
Dropdown Events
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 Docs
Bootstrap Icons

Free, high-quality icon library designed for Bootstrap.

Browse Icons
Continue 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