Tailwind CSS 无法在 React 应用程序中加载背景图像

问题描述 投票:0回答:3

我正在使用 React 和 Tailwind CSS 并尝试为一个 div 设置背景图像。但是,尽管设置了 tailwind.config.js 并将图像保存在正确的位置,但背景图像并未显示。

我是否遗漏了一些东西可以让 Tailwind 正确加载背景图像?

这是我的 tailwind.config.js ,包括我想要加载的名为“background.jpg”的图像

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
      'background': "url('src/images/background.jpg')"
    },
  },
  plugins: [],
}

组件(我在类名中列出了 bg-background):

        <div className="App">
          <div className="container px-2 py-2 min-w-full bg-background">
            <div className="flex h-screen bg-red">
            <div className="m-auto">
           <h1 className="text-5xl">Element Reference App</h1>
           </div>
           </div>
</div>
    </div>

文件结构:

reactjs background-image tailwind-css
3个回答
3
投票

我认为你需要将背景图像文件放在项目的

public
目录中。然后您就可以在 Tailwind 中使用
url('/background.jpg')

当您为生产而构建时,这也将起作用。我怀疑构建后使用

src
目录是否有效,因为它可能不在生产区中。


0
投票

tailwind.config.js 中的扩展部分是错误的。图片必须导出为对象。

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
      'background': "url('src/images/background.jpg')"
    },
  },
  plugins: [],
}

必须更改为

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
     backgroundImage: { 'background': "url('/src/images/background.jpg')" }
    },
  },
  plugins: [],
}

0
投票

回答@MrPatel2021,上面的问题:

但是当背景图像来自 API 时怎么办?如何设置API Tailwind 配置文件中的响应?

要实现这一点,您需要内联完成:

<div className="bg-[url('path-to-your-remote-image.png')]">
  <!-- ... -->
</div>

使用

tailwind-merge
(推荐)或
clsx
lib 来合并或加入其他类名。

© www.soinside.com 2019 - 2024. All rights reserved.