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

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.

Related

Tailwindcss background-image not working in dark mode

I have my Tailwind classes defined like this:
<section class="dark:bg-gray-900 bg-hero-image bg-fixed">
So in the light version a background image is shown and on the dark version just gray-900 as background color.
The image is defined in tailwind.config.js like this:
theme: {
extend: {
backgroundImage: {
'hero-image': "url('/header.jpg')"
},
But this just doesn't work and still shows the image on dark mode.
You have to add backgroundImage to the variants in tailwind.config.js:
module.exports = {
variants: {
extend: {
backgroundImage: ["dark"],
},
},
ALSO you have to add dark:bg-none for the background-image to be set to none.
<section class="dark:bg-gray-900 dark:bg-none bg-hero-image bg-fixed">
This is also nessessary for things like invert and many other classes. Check the corresponding section in the docs, whether or not the variants are included by default.
By default, only responsive variants are generated for invert utilities.
https://v2.tailwindcss.com/docs/invert#variants

Hidden on Custom Breakpoint Breaks All Breakpoints' Display Value in Tailwind

Here is the Tailwind Play code.
I have a configuration as below, mind the custom breakpoint:
const colors = require("tailwindcss/colors");
module.exports = {
darkMode: "media", // or 'media' or 'class'
theme: {
extend: {
screens: {
xs: "320px", // here i have xs
},
colors: {
orange: colors.orange,
},
},
},
variants: {
extend: {},
},
plugins: [],
};
Then I have some elements as below:
<div class="bg-gray-500 xs:hidden sm:hidden md:flex">
<h1>foo</h1>
</div>
I want the div to display on screens above md, otherwise it should be hidden.
The weird thing about the code above is this totally works with built-in breakpoint, sm. For example, if you remove xs:hidden in Tailwind Play. You will see the behavior I want to have.
However, I also want to include xs:hidden. Why does this happen?
Thanks in advance.
Environment
"postcss": "^7.0.39",
"tailwindcss": "npm:#tailwindcss/postcss7-compat#^2.2.17"
Using with React.
To hide and element until a specific width use hidden to hide the element and another display class with responsive modifier (e.g. md:flex) to show it again.
So basically this should fit your needs:
<div class="bg-gray-500 hidden md:flex">
<h1>foo</h1>
</div>
See https://play.tailwindcss.com/Nb0QOhn9E7 for a working snippet.
Combining a responsive hidden (e.g. xs:hidden) and with another responsive display class (e.g. md:flex) doesnt work as the specifity of both css selectors is the same (both use a single class selector inside a mediaquery) so the md:flex does not overwrite it.
Therefore use non-responsive hidden (single class selector) which is less specific then md:flex (single class selector inside a mediaquery) so it gets overwritten for md upwards.
Theres also a issue in tailwind-css github regarding this behaviour:
https://github.com/tailwindlabs/tailwindcss/issues/841

Adding CSS background image to Material UI theme

In material UI, the theme can be adjusted and/or overridden using the createMuiTheme function. This is the full file in which I am doing so:
import { createMuiTheme } from '#material-ui/core/styles';
import purple from '#material-ui/core/colors/purple';
import green from '#material-ui/core/colors/green';
//import wood from './static/wood.png';
const theme = createMuiTheme({
palette: {
primary: {
main: purple[500],
},
secondary: {
main: green[500],
},
},
overrides: {
MuiCssBaseline: {
'#global': {
body: {
border: '2px solid blue',
backgroundImage: 'url("/static/wood.png")',
},
},
},
},
});
export default theme;
The global styling applied to the body is confirmed working- I can see the blue border. However, nothing I try will get the background image to work.
Normally, I would uncomment the import statement at the top: import wood from './static/wood.png'; and then change the CSS line to:
backgroundImage: `url(${wood}),`
However, the import statement alone is causing a crash:
TypeError: Object(...) is not a function. It seems that there is something special about customizing a material ui theme that doesn't allow static assets to be imported in the same file.
When I instead attempt to use a url for the image (shown above), it is always a 404 error. My file structure places the image in src > static > wood.png, but I get:
http://localhost:3000/static/wood.png 404 (not found).
I've tried dozens of possible path variations, but none have worked, and all my efforts to research the proper path just indicate that I'm already using the correct path.
Is it only possible to add a background image to the body using Material UI theme customization when the background image is hosted on a separate server?
The only working examples I've found do it that way (like this one: https://codesandbox.io/s/v30yq681ql), but it seems like there must be a way to use an image stored locally.
Or if the problem really is that my relative path is incorrect, what can I do to find out what the correct one would actually be?
If there is a better way to add a background image to a page with Material UI that would work too, though I haven't seen any other way to do it than a global override of the body tag.
If you put your image within the src folder instead of static, e.g.
src/components/wood.png
Reinstate your import like:
import wood from './components/wood.png';
and then put the backgroundImage to:
backgroundImage: `url(${wood})`,
that should work. The same configuration (with different filename, but in the same location) works for me.

Modifying hover in Tailwindcss

I've noticed that :hover in Tailwindcss uses the defaults hover selector which causes 'stuck' hover states on mobile. Is there a way to modify the :hover function to do a #media(hover:hover) instead?
update: There is now a better way. See this answer by Javier Gonzalez
original:
By far the simplest way is to add your own #media rule to the #responsive-class of rules in tailwind. How you can do that is described in the official tailwind documentation under the topic of custom media queries.
Simply add this to your config:
// tailwind.config.js
module.exports = {
theme: {
extend: {
screens: {
'hover-hover': {'raw': '(hover: hover)'},
}
}
}
}
This translates to #media (hover: hover) { ... } in css. And voila, you could use hover-hover:text-red to display red text only for devices that have hover ability.
To make your own, leave 'raw' as is and change the other two attributes to whatever media query you want. The first attribute hover-hover is what you use in tailwind. The second (hover: hover) is what your actual css #media query looks like. E.g.: hover: none or pointer: coarse.
Now, go ahead and use hover-hover:hover:text-red to modify your hover states.
Might be a bit late but the Tailwind team is already addressing this issue in Tailwind version 3 using a feature flag: https://github.com/tailwindlabs/tailwindcss/pull/8394
Once a new version is published with these changes Starting on tailwindcss v3.1.0, you could include a feature flag in your configuration to look like:
// tailwind.config.js
module.exports = {
future: {
hoverOnlyWhenSupported: true,
},
// ...
}
Yes, just generate the hover variant using a plugin that, besides adding the :hover pseudo-selector, also wraps all of the rules inside an #media(hover:hover) rule:
// tailwind.config.js
const plugin = require('tailwindcss/plugin');
const hoverPlugin = plugin(function({ addVariant, e, postcss }) {
addVariant('hover', ({ container, separator }) => {
const hoverRule = postcss.atRule({ name: 'media', params: '(hover: hover)' });
hoverRule.append(container.nodes);
container.append(hoverRule);
hoverRule.walkRules(rule => {
rule.selector = `.${e(`hover${separator}${rule.selector.slice(1)}`)}:hover`
});
});
});
module.exports = {
plugins: [ hoverPlugin ],
}
The responsive attributes like sm: md: lg: will do those media query job for you. Refer example in the docs. If you dont want to use hover state in mobile device. specify with eg:- sm:hover:no-underline
You can easily create your own hover like below:
// styles.css
#variants hover {
.banana {
color: yellow;
}
}
Then use it like class='hover:banana'
Using arbitrary variants
<button
type="button"
class="
[#media(hover:hover)]:opacity-0
[#media(hover:hover){&:hover}]:opacity-100
">
<!-- ... -->
</button>

CSS className isn't making any changes to Reactjs

I'm currently working with rails and reactjs. I'm having difficulties using css in my reactjs files. It seems like every time i try to use it, no change is being applied at all. In my App.jsx file I have this:
import React from "react";
import styles from "./styles.css";
export default class Register extends React.Component {
render() {
return (
<div className={styles.container}>
<h1> this text should appear to the right </h1>
</div>
);
}
}
And in my styles.css file I have this:
.container {
width:40%;
text-align:right;
}
For the record I am using webpack. Can anyone help me understand why the css isn't having any effect on my jsx components. I've looked all over for help but was unable to put the pieces together.
If it matters, this is how my "config/webpack/development.js" file looks like:
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const environment = require('./environment')
module.exports = environment.toWebpackConfig()
It depends on the webpack loader settings. If you are using css-loader as configured in react-scripts (as of 1.1.5), then the classNames are loaded using {modules: false} option, i.e. global styles, which can be referenced as strings in JSX code:
import "./styles.css";
... className="container" ...
Or you can load local styles using following CSS-file syntax:
:local .container {...
Or edit your webpack.config.js appropriately (see https://github.com/webpack-contrib/css-loader#scope for the official documentation of various options).
seems like you didn't enable an option { modules: true } for css-loader in webpack config
take a look
webpack-contrib/sass-loader#206
https://github.com/webpack-contrib/css-loader#options
Taken from: https://github.com/facebook/create-react-app/issues/1350

Resources