BS5 Background Colors
Bootstrap's background color utilities let you quickly change an element's background to match built-in theme colors or custom tints. Explore various classes for immediate, consistent styling.
Key Topics
Common Background Classes
Use classes like .bg-primary
, .bg-success
, and .bg-danger
to set an element's background color in line with the Bootstrap theme.
<div class="bg-primary text-white p-3">Primary background</div>
<div class="bg-success text-white p-3">Success background</div>
<div class="bg-danger text-white p-3">Danger background</div>
Explanation: Pair a background class with a text color class (like .text-white
) for proper contrast. Use padding classes (e.g., .p-3
) to add spacing.
Additional Utility Classes
Bootstrap also provides tinted backgrounds like .bg-dark
, .bg-light
, and opacity helpers (.bg-opacity-*
) to fine-tune intensity.
<div class="bg-dark text-white p-3">Dark background</div>
<div class="bg-light text-dark p-3">Light background</div>
<div class="bg-warning bg-opacity-75 p-3">Warning background at 75% opacity</div>
Explanation: .bg-opacity-*
adjusts the alpha channel of the background color, allowing partial transparency. The text color should still offer enough contrast.
Colorful Background Demo
Below is a full HTML example illustrating different background color utilities within a single page layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Colorful Background Demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-4">
<div class="bg-primary text-white p-3 mb-3">Primary background section</div>
<div class="bg-success text-white p-3 mb-3">Success background section</div>
<div class="bg-warning bg-opacity-75 p-3 mb-3">Warning background at 75% opacity</div>
<div class="bg-dark text-light p-3">Dark background section</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Explanation: Each section demonstrates a different background color class. The optional .mb-3
utility adds margin between elements.
Key Takeaways
.bg-[color]
classes instantly apply brand or contextual colors to an element's background.- Bootstrap's
.bg-opacity-*
utilities let you control background transparency. - Always ensure sufficient contrast between background and text for readability.