How to use background image with tailwind in next.js? [duplicate] - css

This question already has answers here:
Next.js background-image css property cant load the image
(21 answers)
Closed 9 months ago.
I have a background image in the public folder named bg.png
In the index.js page of the pages folder I want to use that image as a background image
I have install tailwind following the documentation of their official website.
I have already tried this, but it doesn't work.
import BG from "../public/bg.png";
return (
<div
className="bg-scroll"
style={{
backgroundImage: `url(${BG})`,
height: "972px",
}}
>
</div>
)
It doesn't show the image.

Another way is that you can define the image in tailwind.config.js file as lke this
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
backgroundImage: {
'my_bg_image' : "url('../public/bg.png')",
}
},
},
plugins: [],
}
Then use it in the component as bg-my_bg_img directly. No need to import image.
return (
<div
className="bg-scroll bg-my_bg_image h-[972px]"
>
</div>
)

When you have assets in a public folder no need to define all the exact path.
<div
className="bg-scroll"
style={{
backgroundImage: `url('/bg.png')`,
height: "972px",
}}
>
</div>

Here is how you can do it all with Tailwind. You don't need to import the image either.
return (
<div
className="bg-scroll bg-[url('/bg.png')] h-[972px]"
>
</div>
)

Related

Why custom material UI styles not reflecting after deployment?

I was trying to implement a customized material UI element. Here is how I was trying to increase the size of the icon.
Here is my style code:
export const Icon = styled(Box)({
color: "gray",
position: "relative",
"& .css-i4bv87-MuiSvgIcon-root": {
fontSize: "2rem",
},
"&:hover": {
color: "black",
},
});
App.js:
<Icon>{icon}</Icon>
While development the style is showing properly as intended, but when I have deployed my app I could see that the style
"& .css-i4bv87-MuiSvgIcon-root": {
fontSize: "2rem",
}
is not reflecting in my application.
Can someone guide me?
the thing is that you are using MuiSvgIcon-root to add the style but in your styled(Box) see that you have a Box. So you need to add style to the correct css class.
If you inspect the css you will see that with your style code the class used is the MuiBox-root:
I've tried in a react codesanbox with this:
import "./styles.css";
import { styled, Box } from "#mui/material";
const Icon = styled(Box)({
color: "gray",
position: "relative",
"&.MuiBox-root": {
fontSize: "2rem",
":hover": {
color: "black"
}
}
});
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Icon>my icon</Icon>
</div>
);
}
LINK: https://codesandbox.io/s/priceless-zeh-yhgqob?file=/src/App.js
Make their precedence higher by making it important may be some other class overriding it! Check on inspect after deployed version.

How to give path/url for background image in tailwind?

I'm using Tailwind in my React Project. I want to add a background image in a div but it shows the following error:
Module not found: Error: Can't resolve '../../icons/blog-hero-1.png' in 'C:\Users\DELL\frontend-development\aidhumanity-practice-2\src'
I'm adding tailwind class
bg-[url('../../icons/blog-hero-1.png')]
for adding background image and url is relative to the current file and also it's working when added normal image through:
import Hero from "../../icons/blog-hero-1.png"
<div>
<img src={Hero} className="h-full rounded-3xl"></img>
</div>
Can anyone guide how to give the correct url?
Note: I've added a codesandbox example here as well for better demonstration in which I've tried to import background image in "Homepage.js" but it's not working.
https://codesandbox.io/s/background-image-wl9104?file=/src/components/Homepage.js
Well you can achieve the same result with the below approach as well:
In your tailwind.config.js file:
module.exports = {
theme: {
extend: {
backgroundImage: {
'hero': "url('../../icons/blog-hero-1.png')"
}
},
},
plugins: [],
}
You can simply mention bg-hero in you class to implement.

Add gradient as a class in Tailwind css

I want to add this style:
background: linear-gradient(10deg, #AF8800 4.03%, #AA9F1F 6.02%, #A7B334 6.01%)
... to tailwind to be able to add it as a class name. I know that in tailwind we can create classes like this:
bg-[red]
Question: How to do the same action as above with the specified gradient?
you can easily use from and to in your class like
<div class="bg-gradient-to-r from-cyan-500 to-blue-500"></div>
from that's snippet you can gradient from color cyan 500, to blue 500
It is complex gradient so you have to use either arbitrary values or extend Tailwind configuration. Add CSS property almost as it is within square brackets - replace spaces with low dash _. Your class should looks like
<div class="bg-[linear-gradient(10deg,#AF8800_4.03%,#AA9F1F_6.02%,#A7B334_6.01%)] p-10"></div>
If you have less than 3 colors included it may be separated between few "stop-color" classes
<div class="p-10 bg-[linear-gradient(10deg,var(--tw-gradient-stops))] from-[#AF8800_4.03%] via-[#AA9F1F_6.02%] to-[#A7B334_6.01%]"></div>
I've also created this package so you can use bg-gradient-10 instead of bg-[linear-gradient(10deg,var(--tw-gradient-stops))]
If you want to avoid arbitrary variants you may extend configuration for background-image or create static utility plugin
const plugin = require('tailwindcss/plugin')
/** #type {import('tailwindcss').Config} */
module.exports = {
theme: {
extend: {
backgroundImage: {
'my-gradient': 'linear-gradient(10deg, #AF8800 4.03%, #AA9F1F 6.02%, #A7B334 6.01%)'
}
},
},
plugins: [
plugin(function({ addUtilities, addComponents, e, config }) {
addUtilities({
'.bg-my-uitility-gradient': {
'background-image': 'linear-gradient(10deg, #AF8800 4.03%, #AA9F1F 6.02%, #A7B334 6.01%)',
},
})
})
],
}
<div class="p-10 bg-my-gradient"></div>
<div class="p-10 bg-my-uitility-gradient"></div>
DEMO

Tailwind style doesn't seems to be apply inside Material-ui Drawer component in NextJs

I am trying to add styling inside a #mui/material/drawer component using tailwind.
import { Close } from "#mui/icons-material";
import { Box, Drawer, IconButton, TextField } from "#mui/material";
import { useContext} from "react";
import { SearchContext } from "store/context";
export default function SearchDrawer() {
const { search, setSearchMode } = useContext(SearchContext);
return (
<Drawer open={search.searchMode} anchor="bottom">
<Box sx={{ height: "100vh" }} className="bg-red-500">
<IconButton onClick={() => { setSearchMode(!search.searchMode); }}><Close/></IconButton>
<div>
<TextField variant="outlined" sx={{display: 'block'}}/>
<TextField variant="outlined" sx={{display: 'block'}}/>
</div>
</Box>
</Drawer>
);
}
Expected behavior is
<Box sx={{ height: "100vh" }} className="bg-red-500">
This line of code will make whole screen red, But Nothing happen.
Output after render
Tailwind styles are not applying on some of Material-ui components like "Drawer", "Dialog", "ToolTip" This all components are hover over other components.
Tailwindcss classes are not working in Tooltip & Dialog components #33424 - GitHub
This page says to modify material-ui theme,
defaultProps: {
container: rootElement,
},
},
But rootElement is available in Reactjs, How to do it on Nextjs.
this is what worked for me from the official docs :
Remove Tailwind CSS's preflight style so it can use the MUI's preflight instead (CssBaseline).
In your file tailwind.config.js add the following :
//Remove Tailwind CSS's preflight style so it can use the MUI's preflight instead
corePlugins: {
preflight: false,
},
Add the important option, using the id of your app wrapper. For example, #__next for Next.js and "#root" for CRA:
In your file tailwind.config.js add the following (for nextjs add #__next):
//Add the important option, using the id of your app wrapper. For example, #__next for Next.js and "#root" for CRA
important: '#__next',
Your file tailwind.config.js should like like :
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
//Add the important option, using the id of your app wrapper. For example, #__next for Next.js and "#root" for CRA
important: '#__next',
theme: {
extend: {},
},
plugins: [],
//Remove Tailwind CSS's preflight style so it can use the MUI's preflight instead
corePlugins: {
preflight: false,
},
}
Fix the CSS injection order. Most CSS-in-JS solutions inject their styles at the bottom of the HTML , which gives MUI precedence over Tailwind CSS. To reduce the need for the important property, you need to change the CSS injection order. Here's a demo of how it can be done in MUI:
import * as React from 'react';
import { StyledEngineProvider } from '#mui/material/styles';
export default function GlobalCssPriority() {
return (
<StyledEngineProvider injectFirst>
{/* Your component tree. Now you can override MUI's styles. */}
</StyledEngineProvider>
);
}
You can check the official documentation : https://mui.com/material-ui/guides/interoperability/#tailwind-css

Tailwind css backgroundImage doesn't work for me

all,
I'm trying to make tailwinds backgroundImage solution work, and I found help for many other tailwindcss problems here or on github, but not for this.
It's not a complicated task, but still doesn't work.
So as in the documentation, I want to create 2 simple background image to use for multiple viewsize.
It is stated in the documentation https://tailwindcss.com/docs/background-image "By default, only responsive variants are generated for background image utilities."
It means, without any further configuration on variants, I should be able to use it for this purpose.
Here is how my tailwind.conf.js looks like (important part is at the end):
const plugin = require('tailwindcss/plugin')
module.exports = {
purge: [
"./pages/**/*.vue",
"./components/**/*.vue",
"./plugins/**/*.vue",
"./static/**/*.vue",
"./store/**/*.vue"
],
theme: {
extend: {
minHeight: {
'120': '30rem',
},
height: {
'15': '3.75rem',
'17': '4.25rem',
'7': '1.75rem',
'75': '18.75rem',
},
width: {
'15': '3.75rem',
open: '11.875rem',
'75': '18.75rem',
},
margin: {
'7': '1.75rem',
'17': '4.25rem',
'27': '6.75rem',
},
padding: {
'7': '1.75rem',
},
borderWidth: {
'5': '5px',
},
fontSize: {
'5xl': '3.375rem',
'xxl': '1.375rem',
},
boxShadow: {
'lg': '0px 0px 10px #00000033',
'xl': '0px 0px 20px #00000080',
},
gap: {
'7': '1.75rem',
},
inset: {
'10': '2.5rem',
'11': '2.75rem',
'17': '4.25rem',
'1/2': '50%',
},
backgroundImage: {
'hero-lg': "url('/storage/img/sys/lg-hero.jpg')",
'hero-sm': "url('/storage/img/sys/sm-hero.jpg')",
},
}
},
variants: {
opacity: ['group-hover'],
backgroundOpacity: ['group-hover'],
},
plugins: []
}
Just to make sure I included the full content.
And this is how the html looks like:
<div class="bg-hero-sm lg:bg-hero-lg h-24 w-24">
potato
</div>
<div class="h-24 bg-gradient-to-r from-orange-400 via-red-500 to-pink-500"></div>
As I said, nothing special, "npm run dev" finishes witout any error...but if I inspect the element, I cannot see anything related to any background parameter in css. Even the example from documentation doesn't work, which should have to provide a gradient block.
I don't think it's important info, but I use tailwind with laravel.
Can anyone help me with that? I'm desperate, and I'm trying to make it work for days :(I can do workaround using css code in my sass file, but I want to use tailwinds own solution)
Thank you all in advance!
I was having this issue in TailwindCSS 2.2.7 My issue was that my syntax was wrong.
tailwindcss.config.js:
theme: {
backgroundImage: {
'pack-train': "url('../public/images/packTrain.jpg')",
},
App.js
<div className="rounded-lg shadow-lg mb-2 h-screen bg-pack-train flex flex-col sm:mx-8"></div>
The ' and " are critical. For some reason eslint was going in and "cleaning" those characters up on save, which was making it not work. Also, the ../ leading the url was also critical.
If you don't want to extend your theme in the tailwindcss.config.js and want to add the background image directly to your div you can try:
<div className="bg-[url('../public/assets/images/banner.svg')]">
This is the simplest way to get background images working.
Reference: Check under Arbitrary values heading
The background image functionality of tailwindcss has been released in version 1.7.0.
I tested your code in my development environment and it didn't work either since I also had an earlier version of tailwindcss. After upgrading to the latest version, your code has worked fine.
editing your tailwind.config.js
module.exports = {
theme: {
extend: {
backgroundImage: theme => ({
'hero-pattern': "url('/img/hero-pattern.svg')",
'footer-texture': "url('/img/footer-texture.png')",
})
}
}
add name and the URL for your image and use it.
example bg-hero-pattern
u need to add (theme) props to your config
like this:
backgroundImage: (theme) => {
'hero-lg': "url('/storage/img/sys/lg-hero.jpg')",
'hero-sm': "url('/storage/img/sys/sm-hero.jpg')",
},
or url with "../" like this
backgroundImage: (theme) => {
'hero-lg': "url('../storage/img/sys/lg-hero.jpg')",
'hero-sm': "url('../storage/img/sys/sm-hero.jpg')",
},
Hope it works :)
In ^3.1.8 version image path was not working. Then I just put "../" instead of "./"
and it worked. Example:
extend: {
backgroundImage: {
'hero-pattern': "url('../src/assets/images/bg.png')",
}
}
I had to specify a height for my image to be displayed
<div className="h-screen bg-hero"/>
For static image[set is background image] works for me.
First import the image from the static image folder.
import m5 from '../Assets/a2.avif'
Then use it like this.
<div style={{ backgroundImage: `url(${m5})` }}>
module.exports = {content: ["./src/**/*.{html,js}"],theme: {extend{},backgroundImage: {"hero-lg": "url('/src/assets/images/bg.png')","hero-sm": "url('/src/assets/images/bg.png')",},},
class="hero-content bg-hero-sm lg:bg-hero-lg flex-col lg:flex-row-reverse"

Resources