What is the best way to implement a background image using Tailwind in Next.js?

I am facing an issue with displaying a background image in my project.

The image is stored in the public folder and named bg.png.

In the index.js file located in the pages folder, I have attempted to set this image as a background but it seems to not be working.

Following the official documentation of Tailwind CSS, I have successfully installed the framework.

Despite trying the following code snippet, the image does not display:

import BG from "../public/bg.png";

return (
  <div
    className="bg-scroll"
    style={{
      backgroundImage: `url(${BG})`,
      height: "972px",
    }}
  >
  </div>
)

I am unsure why the image is not showing up on my page.

Answer №1

There's no need to specify the complete path when you're dealing with assets in a public folder.

<div
   className="bg-scroll"
   style={{
    backgroundImage: `url('/bg.png')`,
     height: "972px",
    }}
  >
</div>

Answer №2

If you want to set a background image in your project, one way is to define it in the tailwind.config.js file just like this:

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      backgroundImage: {
        'my_custom_bg_image' : "url('../public/background.png')",
      }
    },
  },
  plugins: [],
}

You can then use this background image by applying the class bg-my_custom_bg_image directly within your component, without needing to import the image separately.

return (
  <div
    className="bg-cover bg-my_custom_bg_image h-[972px]"
  >
  </div>
)

Answer №3

Discover the versatility of Tailwind with this easy approach. No need to import the image file separately.

return (
  <div
    className="bg-scroll bg-[url('/bg.png')] h-[972px]"
  >
  </div>
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some methods to design distinct angular ui bootstrap dialogs?

Is there a way to customize angular-ui bootstrap modal dialogs so that they have distinct colors and sizes from each other? I can style them globally for the site but not individually. I came across a similar question, but it only addresses changing all d ...

Optimal approach for fetching data in a Next.js component

I am facing a challenge with my menu component that is displayed globally. What is the most effective way to populate this component with data? I am exploring the static generation feature provided by Next.js, but all of the data fetching recommendations ...

Splitting a CSS hierarchical list into horizontally aligned levels of hierarchy

I am trying to horizontally lay out an ordered list with multiple top level nodes while preserving the vertical layout of child nodes. For example, consider a basic list structure like this: <ol> <li>Top 1 <li>Sub 1</li ...

Is it possible to personalize the error message that appears when React Player is unable to play a video?

I have a scenario involving React Player (https://www.npmjs.com/package/react-player) where the video being shown from a Cloudfront pre-signed URL may not be available. Currently, when a user attempts to play the unavailable video, they are greeted with t ...

The button is disabled once inline CSS is applied to it

I was having issues with the CSS of my buttons being overridden by the user agent stylesheet. To fix this, I used inline CSS to override it. However, a new problem emerged where the buttons became unclickable. Here is the code I am using. Any assistance wo ...

Enhance your bootstrap accordion by incorporating stylish up and down arrows using the <accordion> element

I am currently developing a sophisticated web application using Angular and TypeScript, and I have decided to incorporate accordions in some sections. The setup for these accordions involves TypeScript/Bootstrap as shown below: <accordion> <acco ...

The smooth transition of my collapsible item is compromised when closing, causing the bottom border to abruptly jump to the top

Recently, I implemented a collapsible feature using React and it's functioning well. However, one issue I encountered is that when the collapsible div closes, it doesn't smoothly collapse with the border bottom moving up as smoothly as it opens. ...

Failed validation for Angular file upload

I attempted to create a file validator in the front end using Angular. The validator is quite straightforward. I added a function onFileChange(event) to the file input form to extract properties from the uploaded file. I then implemented a filter - only al ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

State of Active Scroll group

How can I dynamically add the "active" class to a link based on which section it has scrolled to? I want the active state to be applied without a hover effect, only when the corresponding section is currently in view. #pagemenu{ display: block; positio ...

I am attempting to create a webpage with a primary center image and two additional images on either side using PHP or HTML

I have a coding dilemma - I want to display three images in a single row, one in the center, one on the left, and one on the right. However, my current PHP code is causing the left and right images to appear below the center image. How can I adjust my co ...

Obtaining an access token and social media ID from Auth0 for your Next.js application

I need assistance with retrieving the access token and ID token from an Auth0 login The useUser hook currently only provides user information, but I require the access token and social media ID of the user in order to send it to my custom PHP API for data ...

Master the art of using useMutation from react-query: Learn how to handle error messages and success notifications effectively!

Currently in my Next.js project, I have integrated react-query to retrieve data from MongoDB. Within my form, a POST request is sent using the useMutation hook: /*** components ***/ import {Button, InputGroup} from "../index"; import {useMutatio ...

Issue with Slick Slider when expanding collapsible section in Bootstrap 4

Whenever I expand a bootstrap collapse that contains a carousel, only one carousel item appears instead of all. Is this a bug in Bootstrap or Slick Slider? https://i.sstatic.net/T7Orm.jpg Slider $('.remember__carousel').slick({ slidesToShow: ...

What steps can I take to stop Next.js from transmitting source mappings to the browser?

When using Next.js, I noticed that my source files are being sent to the browser and are easily accessible through devtools. This poses a security risk as these files contain sensitive getServerSideProps functions with my API keys. I would greatly appreci ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

Display or conceal several elements upon hover using JQuery and HTML

Here is the current progress I have made: <div style = "position: relative;"> <a href = "#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "positio ...

Achieving Flexbox alignment in a responsive layout

Struggling with achieving a responsive layout using Flexbox. Picture a page filled with panels. The main objective is to display a certain number of panels per row, aligned both horizontally and vertically like the rest. The main issue I am encountering ...

An alternative to Firebug for Internet Explorer

Can anyone suggest a suitable replacement for Firebug that is compatible with IE 7 and 8? I need a tool that allows me to edit CSS/HTML in real-time, debug JavaScript code, and visualize the positions of elements on web pages. Appreciate any recommendati ...

serving/download of video and images from AWS S3

As the title implies, I am currently working on a project in my Nextjs app where I need to retrieve files from S3, make them downloadable, and display them. Unfortunately, I am encountering an issue where the files are not displaying or downloading correct ...