How to add background image using Tailwind CSS in React

In this post you will learn how to add background image in Tailwind CSS using react Js through steps.

Step 1: Build a Home Component

The first step will be to add a home component in reactjs that contains a background image from unsplash image.

Lets use the below code to add the background image in reactJs component.

import React from 'react';

const Home= () => {
  

  return (
    <div className="bg-cover bg-center h-96 w-96" style={{backgroundImage: "url('https://images.unsplash.com/photo-1517404215738-15263e9f9178')"}}>
      
    </div>
  );
};

export default Home;

In the return you have style and className attribute for adding the background image from the url. Inside the attribute you used the backgroundImage: “url(‘your_path_of_image’)” to load the image.

Also in the class I used the height and width of 385px .

Step 2: Run the reactjs app

Now go to the terminal and type the npm start to run the app. You will get the output as below when you go to the “http://localhost:3000/”.

Thats all you have to do to add background image in tailwind css using reactjs. You can also add some styling to look the background image beautiful.

  1. m-10 : To add margin of 10px all around the image.
  2. shadow-2xl : Add box shadow aroung the image.
  3. shadow-slate-700/100 : Change the color of the shadow.
import React from 'react';

const Index = () => {
  

  return (
    <div className="m-10 shadow-2xl bg-cover bg-center h-96 w-96" style={{backgroundImage: "url('https://images.unsplash.com/photo-1517404215738-15263e9f9178')"}}>
      
    </div>
  );
};

export default Index;

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link