Home > Back-end >  How to make an svg image as a background image with react and Tailwind css?
How to make an svg image as a background image with react and Tailwind css?

Time:05-18

i am implementing a reponsive website with react and tailwind , i have an SVG image which i want to make it as a background image for a main tag but it doesn't work . I followed the tailwind docs and added this code to my taliwind.config.js

 theme: {
   extend: {
      backgroundImage: {
                         'hero-pattern': "url('/public/background.svg)"
                        }
            }
         }

and using bg-hero-pattern does not display anything . I tried another option which is the style attribute in my tag it displays the image but it does not cover all the parent tag although i am using bg-cover and bg-no-repeat this is my code :

<main className="w-screen h-screen  ">
    <div className="h-screen w-screen bg-no-repeat bg-cover"                    
         style={{ backgroundImage: `url(${background})` }}>
      {/* Content */}
      
      <div className="px-4 py-6 sm:px-0">
        <div className="border-4 border-dashed border-gray-200 rounded-lg h-96"> 
     </div>
      </div>
      {/* <!-- /End content --> */}
    </div>
  </main>

can anyone help me please ?

CodePudding user response:

I tend to avoid using background images these days and use grid instead. Just layer the grid cells one on top of the other.

https://play.tailwindcss.com/gOFytBrc4G

<div >
  <img src="/img/logo.svg"  alt="Tailwind Play" />
  <div >
    <h1 >This is my heading</h1>
  </div>
</div>

You can wrap the img in a div if that gives you more control.

It should give the same end result, and I find you have more control this way anyway.

CodePudding user response:

The simplest and best solution could be using an arbitrary value. You can do something like this

<div className="bg-[url('../images/background-image.svg')]">

You can find more details about arbitrary values over here and you require tailwind version 3 to use it.

  • Related