Tailwind CSS Backgrounds
Backgrounds are an important component of building UI visual hierarchy and style. Tailwind provides comprehensive utility classes for controlling background colors, gradients, images, and sizes.
Background Color
Use bg-{color} utility classes to set an element's background color. You can use the entire color palette defined in tailwind.config.js.
<div class="bg-sky-500 text-white p-4">
This is a div with a blue background.
</div>
<button class="bg-emerald-500 hover:bg-emerald-600 ...">
A green button
</button>You can also use bg-opacity-{amount} to control the opacity of the background color.
<div class="bg-blue-500 bg-opacity-75 ...">...</div>Gradient Colors
Tailwind makes it easy to create smooth color gradients. You need to combine three utility classes:
Define gradient direction:
bg-gradient-to-{direction}bg-gradient-to-t: to topbg-gradient-to-br: to bottom rightbg-gradient-to-r: to right (default)
Define starting color:
from-{color}Define ending color:
to-{color}(Optional) Define middle color:
via-{color}
<!-- A gradient from purple to pink -->
<div class="bg-gradient-to-r from-purple-500 to-pink-500 h-24"></div>
<!-- A three-color gradient -->
<div class="bg-gradient-to-br from-green-400 via-blue-500 to-purple-600 h-24"></div>Background Image
You can use arbitrary values like bg-[url(...)] to set a background image.
<div class="bg-[url('/img/hero-pattern.svg')] h-48">
<!-- ... -->
</div>Background Size, Position, and Repeat
When using background images, you usually need to control their size, position, and repetition.
Background Size:
bg-{size}bg-auto: (default)bg-cover: Scale image to completely cover the element, may crop the image.bg-contain: Scale image to completely fit within the element, may leave empty space.
Background Position:
bg-{position}bg-center: Centerbg-top: Top alignmentbg-left-bottom: Bottom-left alignment
Background Repeat:
bg-repeat,bg-no-repeat,bg-repeat-x,bg-repeat-y
<div
class="bg-[url('/img/image.jpg')] bg-cover bg-center bg-no-repeat h-64 rounded-lg"
>
<!-- A common card background image setup -->
</div>By combining these background utility classes, you can create rich, colorful, and attractive visual effects for your website and components.