Explain Codes LogoExplain Codes Logo

How to access all the direct children of a div in tailwindcss?

html
responsive-design
tailwindcss
css
Alex KataevbyAlex Kataev·Jan 2, 2025
TLDR

Access direct children in TailwindCSS by utilizing the > selector in CSS within the @apply directive:

.parent > * { @apply bg-blue-500 p-4; }

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:

<div class=">& bg-blue-500 ...">...</div>

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:

.parent > .child { @apply text-gray-200; } // Distinguish child without DNA Test

For a more targeted approach, denote child variants in tailwind.config.js:

// In tailwind.config.js module.exports = { // ... variants: { extend: { textColor: ['child'], }, }, }

You can utilize these in HTML for applying styles like:

<div class="child:text-gray-200">...</div> // Presto! Direct children only.

Creating custom variants

When default variants aren't sufficient, tailor your styling rules with Tailwind's AddVariant feature:

// In tailwind.config.js const plugin = require('tailwindcss/plugin') module.exports = { plugins: [ plugin(function ({ addVariant }) { addVariant('child-hover', ({ container, separator }) => { container.walkRules(rule => { rule.selector = `.child-hover${separator}${rule.selector.slice(1)}:hover > *` // Hover effect, not the UFO one )) }) }) }) } }

With this custom variant, you can apply child-hover:text-blue-500 like:

<div class="child-hover:text-blue-500">...</div> // Hover to show some colors!

Harnessing plugins

Plugins extend Tailwind's functionalities. For instance, the tailwindcss-children plugin eases the chore of selecting children:

  1. Install the plugin:
npm install tailwindcss-children --save-dev // Plug it in, plug it in!💡
  1. Include it in your tailwind.config.js file:
module.exports = { plugins: [ require('tailwindcss-children'), ], }

You can now use it in your classes:

<div class="children:p-4"> ... </div> // When parenting gets tough, plugin!

Applying base styles

Broaden your style with @layer base and @apply. These expand your direct child styling capabilities:

@layer base { .parent > * { @apply text-gray-200; // Kids, it's the law! 😁 } }

This snippet will ensure that all direct children within .parent inherit text-gray-200.