'How to access all the direct children of a div in tailwindcss?
I have this html:
<div class="section">
<div class="header">header</div>
<div class="content">
<div>sub contents 1</div>
<div>sub contents 2</div>
</div>
</div>
I want to access the direct children of div with class "section" which would be divs with class: "header" and "content".
I know with css we can do: div.section > div
But how to do this using tailwindcss?
Solution 1:[1]
By default you can't. However I use these simple lines in tailwind.config.js
to give me child
and child-hover
options.
plugins: [
function ({ addVariant }) {
addVariant('child', '& > *');
addVariant('child-hover', '& > *:hover');
}
],
Then use like this
<div class="child:text-gray-200 child-hover:text-blue-500">...</div>
Which will give every child a gray textcolor, and a blue one on hover.
See here for more information on adding variants using a plugin
Solution 2:[2]
If you want to access the direct children of div with selector, please use @layer
directive. see below:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
div.section > div {
@apply text-xl;
}
}
Solution 3:[3]
This is tailwind v1&v2 version of Willem Mulder's.
only change is variant name children
instead of child
plugin(function({ addVariant, e }) {
addVariant('children', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
const newClass = e(`children${separator}${className}`);
return [
`.${newClass} > *`,
// `.${newClass}:hover `,
].join(",");
});
});
addVariant('children-first', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
const newClass = e(`children-first${separator}${className}`);
return [
`.${newClass} > *:first-child`,
].join(",");
});
});
}),
add variants for padding
variants: {
padding: ['responsive', 'children', 'children-hover', 'children-first', ],
},
Solution 4:[4]
This is currently not possible and probably won't be implemented soon.
Instead, I recommend using this plugin: https://github.com/benface/tailwindcss-children. Follow the README for further instructions.
Usage:
After you have installed the plugin and added it to your tailwind.config.js
, you can access direct children by adding children:{your_style}
to the parent class. If you for example would want to add p-4
to header
and content
, your code would look like this:
<div class="section children:p-4">
<div class="header">header</div>
<div class="content">
<div>sub contents 1</div>
<div>sub contents 2</div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Willem Mulder |
Solution 2 | GeckoTang |
Solution 3 | |
Solution 4 |