Added in v5.2

Color and background

Set a background color with contrasting foreground color.

Overview

Color and background helpers combine the power of our .text-* utilities and .bg-* utilities in one class. Using our Sass color-contrast() function, we automatically determine a contrasting color for a particular background-color.

Heads up! There’s currently no support for a CSS-native color-contrast function, so we use our own via Sass. This means that customizing our theme colors via CSS variables may cause color contrast issues with these utilities.

Color & background - 图1

html

  1. <div class="text-bg-primary p-3">Primary with contrasting color</div>
  2. <div class="text-bg-secondary p-3">Secondary with contrasting color</div>
  3. <div class="text-bg-success p-3">Success with contrasting color</div>
  4. <div class="text-bg-danger p-3">Danger with contrasting color</div>
  5. <div class="text-bg-warning p-3">Warning with contrasting color</div>
  6. <div class="text-bg-info p-3">Info with contrasting color</div>
  7. <div class="text-bg-light p-3">Light with contrasting color</div>
  8. <div class="text-bg-dark p-3">Dark with contrasting color</div>

Accessibility tip: Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies like screen readers. Please ensure the meaning is obvious from the content itself (e.g., the visible text with a sufficient color contrast) or is included through alternative means, such as additional text hidden with the .visually-hidden class.

With components

Use them in place of combined .text-* and .bg-* classes, like on badges:

Color & background - 图2

html

  1. <span class="badge text-bg-primary">Primary</span>
  2. <span class="badge text-bg-info">Info</span>

Or on cards:

Color & background - 图3

html

  1. <div class="card text-bg-primary mb-3" style="max-width: 18rem;">
  2. <div class="card-header">Header</div>
  3. <div class="card-body">
  4. <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
  5. </div>
  6. </div>
  7. <div class="card text-bg-info mb-3" style="max-width: 18rem;">
  8. <div class="card-header">Header</div>
  9. <div class="card-body">
  10. <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
  11. </div>
  12. </div>