tailwind - some class not works - next.js

I use tailwind in nextjs project, and when I restart the server (I mean start the server again with npm run dev) some tailwind code not working when I write class property in "inspect Element" it works but not tailwind code.
not works: w-1/2 (width: 25%), lg:w-0 (media screen and(max-width: 1024px) {code})
my tailwind.config.js
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
screens: {
sm: { max: "640px" },
md: { max: "768px" },
lg: { max: "1024px" },
xl: { max: "1280px" },
"2xl": { max: "1536px" },
}
},
plugins: [],
};
my global.css file:
#tailwind base;
#tailwind components;
#tailwind utilities;
#import "./reset.css";

You need to pass the classes fully w-1/2 instead of partially like 1/2. As tailwind doesn't support dynamic classes.
Try the following code.
function Component({ width}) {
return (
<div
className={`${width}`}
>
Hello there
</div>
);
}
And use it as
<Component
width={"w-1/2"}
/>
Edit: Using Safelisting classes
As a last resort, Tailwind offers Safelisting classes
Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature.
In your example,you want to have different width. You can use regular expressions to include all the widths you want using pattern
In tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
{
pattern: /w-(1/2|2/2|1/6|2/6)/, // You can define all the width you desire
},
],
// ...
}

you have to create an extend object with your personalized code inside like this:
theme: {
extend: {
screens: {
'clg': '1090px',
'cxl': '1159px',
'c2xl': '1213px',
'c3x1': '1373px',
'c4x1': '1480px',
'c5x1': '1579px',
'c6x1': '1679px',
'c7x1': '1740px',
'c8x1': '1820px',
},

Related

Tailwind media queries for padding

I cannot make a simple media query for the padding of an element. I work with NextJs but it is not the problem because my custom break points work for everything else but this :
When I have a class like className="p-2 sml:p-4" the p-2 overwrites the other class. I think it has to do with the !important attribute given to p-2 by tailwind.
How to make this simple thing ? What am I missing ?
PS: I repeat, this problem has nothing to do with the media query itself, className="bg-black sml:bg-white" works perfectly fine. The sml: is my custom media query that is triggered at 576px, and I repeat, works very well.
Edit: Minimal code to reproduce
<main className="p-2 sml:p-4">
<div className="w-full h-12 bg-black"/>
</main>
Edit: Config file for tailwind version 3.1.2
/** #type {import('tailwindcss').Config} */
module.exports = {
important: false,
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
plugins: [
require('tw-elements/dist/plugin')
],
darkMode: 'class',
theme: {
screens: {
'sml': '576px',
'mdm': '768px',
'nrm': '992px',
'lrg': '1280px',
'max': '1564px',
},
extend: {
},
},
plugins: [],
}
As you said, the problem is that the !important attribute is added to the p-2 class. You can disable whether or not Tailwind's utilities should be marked with !important in your tailwind.config.js file:
module.exports = {
important: false,
}
Reference: https://tailwindcss.com/docs/configuration

Problem with #tailwind base in own .css (Unknown at rule #tailwindcss(unknownAtRules)

I have a problem with custom css in tailwind and vite.
My maian.js look like:
import "./styles.css";
// import "tailwindcss/tailwind.css";
document.querySelector("#app").innerHTML = `
<h1>Hello Vite!</h1>
Documentation
`;
My styles.css looks like:
#tailwind base;
#tailwind components;
#tailwind utilities;
.header-nav-section {
#apply bg-gradient-to-br from-gray-100e to-gray-300;
}
But vscode informed me that:
What is wrong, I readed documentation and this case will working.
P.S
Full repo:
https://github.com/mxcdh/vite-tailwind
Follow the following steps
Add the the following Custom Data for CSS file css_custom_data.json.
Declare it into the VSCode settings file.
.vscode/settings.json:
{
"css.customData": [".vscode/css_custom_data.json"]
}
.vscode/css_custom_data.json:
{
"version": 1.1,
"atDirectives": [
{
"name": "#tailwind",
"description": "Use the `#tailwind` directive to insert Tailwind's `base`, `components`, `utilities` and `screens` styles into your CSS.",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#tailwind"
}
]
},
{
"name": "#responsive",
"description": "You can generate responsive variants of your own classes by wrapping their definitions in the `#responsive` directive:\n```css\n#responsive {\n .alert {\n background-color: #E53E3E;\n }\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#responsive"
}
]
},
{
"name": "#screen",
"description": "The `#screen` directive allows you to create media queries that reference your breakpoints by **name** instead of duplicating their values in your own CSS:\n```css\n#screen sm {\n /* ... */\n}\n```\n…gets transformed into this:\n```css\n#media (min-width: 640px) {\n /* ... */\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#screen"
}
]
},
{
"name": "#variants",
"description": "Generate `hover`, `focus`, `active` and other **variants** of your own utilities by wrapping their definitions in the `#variants` directive:\n```css\n#variants hover, focus {\n .btn-brand {\n background-color: #3182CE;\n }\n}\n```\n",
"references": [
{
"name": "Tailwind Documentation",
"url": "https://tailwindcss.com/docs/functions-and-directives#variants"
}
]
}
]
}
If thisn't work , Try to update your node.js to the latest current stable version and try again
Does your tailwind work? Could just be a faulty installation.
Otherwise try installing the official vscode extension or disable custom at rules validation
If you are working in VSCode, you need to disable the lint rule of unknownAtRules.
RECOMMENDED FIX:
Create .vscode at the root of your project
Create file named settings.json
Identify the filetype you are using for example css or scss
Create an empty json object {}
Inside json object add, "[FILE EXTENSION OF STEP 3].lint.unknownAtRules": "ignore"
here is how the file will look like in the case of scss extension:
.vscode > settings.json
{
"scss.lint.unknownAtRules": "ignore"
}
It helps you push the change in git and share the fix with the team.
SECOND WAY:
Do the same as explained above inside your VSCode Global settings.json. It will fix the problem for you but not for others using the same codebase. You can open the file by using, Cmd+Shift+P and then choosing "Preferences: Open Settings (JSON)".
Usually, it fixes the issue right away, but you can reload browser if needed.
Fix: For vue use "css.lint.unknownAtRules": "ignore". Credits => #zijizhu
https://github.com/tailwindlabs/tailwindcss/discussions/5258
https://flaviocopes.com/fix-unknown-at-rule-tailwind/#:~:text=Here's%20how%20to%20fix%20this,Done!

Use Color in TailWind CSS

How to use Color in TailWind CSS ?
I am learning TailWind CSS.I am using TailWind CSS in Laravel.
My tailwind.config.js is like below
const { colors } = require('tailwindcss/defaultTheme')
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
colors: {
cadetblue:'#5f9ea0',
},
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
I declared CSS inside <head></head> is like below.
<style>
.hello { background-color: theme('colors.cadetblue'); }
</style>
I am using .hello class in HTML like below.
<div class="hello">Hello</div>
But this is not working.
Firstly, you need to define colors object array in your custom theme file, because your tailwind config will overide the default. So please check your colors import is same with official doc,
const colors = require('tailwindcss/colors')
Solution 1
Define your custom color name into theme.colors
const colors = require("tailwindcss/colors");
module.exports = {
purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
...
theme: {
...
colors: {
cadetblue: "#5f9ea0",
},
...
Solution 2
In other way, you can simplly adjust it with define in your main css file like this, Official Doc Link
// in your css file
#tailwind base;
#tailwind components;
#tailwind utilities;
...
# You can add your custom class name into `utilities`
#layer utilities {
.bg-cadetblue {
background-color: #5f9ea0;
}
}
and use it
<div class="bg-cadetblue">Hello</div>
ps, restart your app with npm run start or yarn start required!
Happy coding :)
In tailwind-3 you could pass the exact color inline if you use [ ]:
<div class="bg-[#5f9ea0]">Hello</div>

not able to use custom classes in #apply in scss file tailwind nextjs project?

I'm trying to use a custom class overflow:inherit as #apply overflow-inherit in tailwind next.js project but it's throwing error. However, I can #apply pre-built tailwind classes like #apply flex flex-col md:h-full h-screen; but not custom.
Full repo: https://github1s.com/GorvGoyl/Personal-Site-Gourav.io
tailwind.scss:
#tailwind base;
#tailwind components;
#tailwind utilities;
#layer utilities {
#variants responsive {
.overflow-inherit {
overflow: inherit;
}
}
}
project.module.scss:
.css {
:global {
.wrapper-outer {
#apply overflow-inherit; //trying to apply custom utility
}
}
}
Error:
wait - compiling...
event - build page: /next/dist/pages/_error
error - ./layouts/css/project.module.scss:4:6
Syntax error: C:\Users\1gour\Personal-Site\project.module.scss The `overflow-inherit` class does not exist, but `overflow-hidden` does. If you're sure that `overflow-inherit` exists, make sure that any `#import` statements are being properly processed before Tailwind CSS sees your CSS, as `#apply` can only be used for classes in the same CSS tree.
2 | :global {
3 | .wrapper-outer {
> 4 | #apply overflow-inherit;
| ^
5 | }
6 | }
postcss.config.js:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
"next": "^10.0.7",
"tailwindcss": "^2.0.3",
"sass": "^1.32.8",
"postcss": "^8.2.6",
I had the same problem on my Laravel project.
I decided that postcss is not enough for me. So in the webpack.mix.js I deleted the following
mix.postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]);
and replaced it with sass like this
mix.sass("resources/css/app.scss", "public/css").options({
postCss: [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
], });
Now, I got a number of cool features including the one you want
I don't even need to use #layer
in my scss file I can combine #apply and #extend and it works
.btn-my-theme{
#apply rounded border py-2 px-3 shadow-md hover:shadow-lg;
}
.btn-my-primary{
#extend .btn-my-theme;
#apply text-blue-600 bg-blue-200 hover:bg-blue-100 border-blue-500;
}
.btn-my-secondary{
#extend .btn-my-theme;
#apply text-gray-600 bg-gray-200 hover:bg-gray-100 border-gray-500;
}
Set CSS validate in "Workspace/.vscode/settings.json"
"css.validate": false,
or "User/settings.json"
"css.validate": false,
like this link

Use tailwind #apply in CSS modules in Next.js

I've setup tailwind with my Next.js site as per the official guide here: https://github.com/tailwindcss/setup-examples/tree/master/examples/nextjs
However, when I try and use the #apply method, in a CSS module on a component level, eg:
.container {
#apply rows-span-3;
}
I get the following error:
Syntax error: #apply cannot be used with .rows-span-3 because .rows-span-3 either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that .rows-span-3 exists, make sure that any #import statements are being properly processed before Tailwind CSS sees your CSS, as #apply can only be used for classes in the same CSS tree.
This is my postcss.config.js:
const purgecss = [
'#fullhuman/postcss-purgecss',
{
content: ['./components/**/*.jsx', './pages/**/*.jsx'],
defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
},
]
module.exports = {
plugins: [
'postcss-flexbugs-fixes',
'postcss-import',
'postcss-mixins',
'postcss-calc',
'postcss-extend',
['postcss-color-mod-function', {
importFrom: [
'./assets/styles/vars.css',
],
}],
['postcss-preset-env', {
stage: 1,
preserve: false,
importFrom: [
'./assets/styles/vars.css',
],
}],
'tailwindcss',
'autoprefixer',
...(process.env.NODE_ENV === 'production' ? [purgecss] : []),
'postcss-nested',
],
}
I manage to make it work using this example
link to tailwind doc
From the doc:
You have this module css
/*Button.module.css*/
.error {
#apply bg-red-800 text-white;
}
Component file
//Button.js
import styles from './Button.module.css'
export function Button() {
return (
<button
type="button"
// Note how the "error" class is accessed as a property on the imported
// `styles` object.
className={styles.error}
>
Destroy
</button>
)
}
From the example, please notice the use of className={styles.error} instead of className="error"

Resources