Add Background Image Using Custom Tailwind CSS Configuration
How to add background image using TailwindCSS with the help of custom configuration
Tailwind CSS is a popular utility-first CSS framework that simplifies the process of styling your web elements. In the case of designing a website or web application, one of the common tasks is adding background images to elements, and Tailwind makes this very straightforward with custom configuration. In this article, we will walk you through the steps to add a background image using Tailwind CSS custom configuration, as well as explain some useful Tailwind classes that can help you customize the image behavior.
Step 1: Configuration for Background Images
You can define your image path using url() in tailwind.config file. You need to add the image inside the backgroundImage section.
backgroundImage: {
bannerImg: "url('/travel-banner.jpg')",
}
Step 2: Use The Class Names in Your HTML
You can add your image with bg utility class then mentioning your image class name.
<section className="bg-bannerImg">
...
</section>
Step 3: Add Background Image Properties with Tailwind Classes
After the background image is set, you can control how it behaves using a few key utility classes provided by Tailwind CSS.
<section className="bg-bannerImg bg-repeat bg-cover bg-bottom">
...
</section>
1. Background Repeat
By default, the background image might repeat if it's smaller than the container. You can control this with Tailwind's bg-repeat classes.
bg-no-repeat: Prevents the image from repeating.
bg-repeat: Repeats the image in both directions.
bg-repeat-x: Repeats the image only on the horizontal axis.
bg-repeat-y: Repeats the image only on the vertical axis.
2. Background Size
You can also control the image aspect ratio using background size utilities.
bg-cover: Scales the background image to cover the entire container while maintaining the aspect ratio.
bg-contain: Scales the background image to fit within the container, without stretching it.
3. Background Position
You can control the position of the background image using the bg-position utilities.
bg-top: Positions the image at the top.
bg-center: Centers the background image.
bg-bottom: Aligns the image at the bottom.
4. Background Attachment
Tailwind allows you to control whether the background image scrolls with the content or is fixed in place.
bg-fixed: Fixes the background image.
bg-scroll: The background image scrolls with the page.
Conclusion
Adding a background image to your website or web application is fast and easy with the help of Tailwind CSS. Tailwind offers a range of utilities that allow you to control how the background behaves, without needing to write custom CSS from scratch. Whether you're setting background size, positioning, repeating, even attachment. Tailwind simplifies the entire process and helps you to design responsive and visually appealing elements with minimal effort.