Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style nested elements based on parent class using Tailwind CSS?

Let's say I want all the links inside white card to be black, and all the links inside orange cards to be white. I can easily do in pure CSS:

.card--primary {
  background-color: white;

  a {
    color: black
  }
}

.card--danger {
  background-color: orange;
  
  a {
    color: white;
  }
}

But how can I achieve similar behaviour using Tailwind (or other CSS utility frameworks)?

like image 438
Andrew Avatar asked Sep 01 '25 05:09

Andrew


2 Answers

This is possible in tailwind 3.1 with the addition of the arbitrary variants feature. The way you would do this is by using a selector on the parent div:

<div className="card--primary bg-white [&>a]:text-black" >
  <a/>
  <a/>
<div/>

<div className="card--danger bg-orange [&>a]:text-white" >
  <a/>
  <a/>
<div/>
like image 119
OneTuskedMario Avatar answered Sep 02 '25 19:09

OneTuskedMario


In case of Tailwind CSS

Read the descriptive and a very brief documentation entry here: Using arbitrary variants.

As I can see you need to change the color of all the <a> links no matter how deeply they reside in the <cards>. Use an underscore between & and a selectors - [&_a]:text-black. This translates to:

.card--primary {
      
  /* arbitrarily nested <a> links */
  a {
    color: black
  }
}

On the other hand the Tailwind directive with > between & and a => [&>a]:text-black would result in this css (only the direct child <a> nodes would be styled):

.card--primary {
      
  /* direct-child <a> links */
  > a {
    color: black
  }
}

Recap: the resulting Tailwind HTML for your case:

<div className="card--primary [&_a]:text-black" >
  <a></a> !-- will be black
  <div>
    <a></a> !-- will be black
  </div>
<div/>

<div className="card--danger [&_a]:text-white" >
  <a></a> !-- will be white
  <div>
    <a></a> !-- will be white
  </div>
<div/>

That's it. I hope it is helpful.

like image 25
Zmyślny Avatar answered Sep 02 '25 19:09

Zmyślny