0
0
BootstrapHow-ToBeginner · 3 min read

How to Create Badge in Bootstrap: Simple Guide with Examples

To create a badge in Bootstrap, use the span or button element with the class badge and a color class like bg-primary. Badges are small count or label indicators that can be added to text or buttons easily.
📐

Syntax

Use a span or button element with the badge class. Add a background color class like bg-primary, bg-success, or bg-danger to style the badge color.

  • badge: base class for badges
  • bg-primary: blue background color
  • bg-success: green background color
  • bg-danger: red background color
html
<span class="badge bg-primary">Primary</span>
Output
A small blue pill-shaped badge with the text 'Primary'.
💻

Example

This example shows badges used inside buttons and next to text. It demonstrates how badges highlight counts or labels.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap Badge Example</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-3">
  <h1>Notifications <span class="badge bg-danger">3</span></h1>
  <button type="button" class="btn btn-primary">
    Messages <span class="badge bg-secondary">7</span>
  </button>
  <p>New updates <span class="badge bg-success">New</span></p>
</body>
</html>
Output
A heading with a red badge showing '3', a blue button with a gray badge showing '7', and a paragraph with a green badge labeled 'New'.
⚠️

Common Pitfalls

Common mistakes include:

  • Not including a background color class like bg-primary, which makes the badge invisible.
  • Using deprecated classes like badge-primary from older Bootstrap versions.
  • Placing badges inside inline elements without spacing, causing layout issues.
html
<!-- Wrong: missing bg color class -->
<span class="badge">5</span>

<!-- Right: with bg color class -->
<span class="badge bg-primary">5</span>
Output
The first badge is invisible or very faint; the second badge is a visible blue pill-shaped badge with '5'.
📊

Quick Reference

Use these classes to create badges:

ClassDescription
badgeBase class for all badges
bg-primaryBlue background color
bg-secondaryGray background color
bg-successGreen background color
bg-dangerRed background color
bg-warningYellow background color
bg-infoLight blue background color
bg-lightLight background with dark text
bg-darkDark background color

Key Takeaways

Always use the base class badge with a background color class like bg-primary to make badges visible.
Badges can be added to text, buttons, or links to show counts or labels.
Avoid using outdated badge classes from older Bootstrap versions.
Use spacing around badges to keep layout clean and readable.
Bootstrap badges are small, rounded, and designed to stand out with color.