Published on

How to Access Direct Children of a Div in TailwindCSS

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Access Direct Children of a Div in TailwindCSS

When working with TailwindCSS, you may want to apply styles specifically to the direct children of a parent element, similar to using > in CSS. This guide covers multiple approaches, including arbitrary variants, plugins, and built-in Tailwind features.

1. Using Arbitrary Variants (Tailwind 3.1+)

Since TailwindCSS v3.1, you can use arbitrary variants to apply styles to direct children.

Example:

<div class="[&>*:hover]:text-blue-500 [&>*]:p-4">
  <div>Child 1</div>
  <div>Child 2</div>
</div>

Explanation:

  • [&>*]:p-4 → Applies p-4 to all direct children.
  • [&>*:hover]:text-blue-500 → Changes text color on hover.

2. Using Tailwind’s Native Child Selectors (Tailwind 3.3+)

As of December 2023, Tailwind introduced built-in child selectors using *: syntax.

Example:

<div class="*:p-4 hover:*:text-blue-500">
  <div>Child 1</div>
  <div>Child 2</div>
</div>

Explanation:

  • *:p-4 → Applies p-4 to all direct children.
  • hover:*:text-blue-500 → Applies hover effect to children.

3. Using Custom Plugins

For older Tailwind versions, you can add a custom plugin in tailwind.config.js to define a child variant.

Example:

// tailwind.config.js
plugins: [
  function ({ addVariant }) {
    addVariant('child', '& > *')
    addVariant('child-hover', '& > *:hover')
  },
]

Usage:

<div class="child:text-gray-700 child-hover:text-blue-500">
  <div>Child 1</div>
  <div>Child 2</div>
</div>

4. Using @layer Directive

If you prefer CSS-based styling, you can use Tailwind’s @layer directive.

Example:

@layer base {
  .section > div {
    @apply p-4 text-gray-700;
  }
}

Usage:

<div class="section">
  <div>Header</div>
  <div>Content</div>
</div>

FAQs

1. What is the best way to style direct children?

Using *:p-4 (Tailwind 3.3+) or [&>*]:p-4 (Tailwind 3.1+) is the simplest method.

2. Can I select all descendants, not just direct children?

Yes! Use [_*]:p-4 instead of [&>*]:p-4 for all nested elements.

3. Will this work with responsive utilities?

Yes, just add breakpoints:

<div class="md:*:p-4 lg:*:p-6">
  <div>Child 1</div>
  <div>Child 2</div>
</div>

By using these methods, you can easily target direct children in TailwindCSS.