How to access all the direct children of a div in tailwindcss?
Access direct children in TailwindCSS by utilizing the > selector in CSS within the @apply directive:
This applies the bg-blue-500 and p-4 classes to immediate child elements of .parent.
Facilitating Tailwind 3.1, you can employ the >& prefix with utility classes for a more streamlined syntax:
Unleashing Tailwind child selectors
TailwindCSS extends a variety of methods to govern child element styling. Here's how you can rule over your John Hancock:
Utilizing >& operator and child variants:
The >& operator in Tailwind directly targets child elements, resembling the CSS div.section > div:
For a more targeted approach, denote child variants in tailwind.config.js:
You can utilize these in HTML for applying styles like:
Creating custom variants
When default variants aren't sufficient, tailor your styling rules with Tailwind's AddVariant feature:
With this custom variant, you can apply child-hover:text-blue-500 like:
Harnessing plugins
Plugins extend Tailwind's functionalities. For instance, the tailwindcss-children plugin eases the chore of selecting children:
- Install the plugin:
- Include it in your
tailwind.config.jsfile:
You can now use it in your classes:
Applying base styles
Broaden your style with @layer base and @apply. These expand your direct child styling capabilities:
This snippet will ensure that all direct children within .parent inherit text-gray-200.
Was this article helpful?