Home > OS >  How to style nested elements based on parent in Tailwind CSS?
How to style nested elements based on parent in Tailwind CSS?

Time:07-02

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 Tailwing? (Or other CSS utility frameworks)?

CodePudding user response:

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/>

CodePudding user response:

YOu can do this way

<script src="https://cdn.tailwindcss.com"></script>
<div >
<div >
    <div >
      
      <div >
        <div >
          <p>White Card with all black links:</p>
          <ul >
            <li >
              
              <a href="https://tailwindcss.com"> First Link</a>
            </li>
            <li >
              
               <a href="https://tailwindcss.com"> Second Link</a>
            </li>
            <li >
              
               <a href="https://tailwindcss.com"> Third Link</a>
            </li>
          </ul>
          </div>
       
      </div>
    </div>
  </div>


  <div >
    <div >
      
      <div >
        <div >
          <p>Orange Card with all white links:</p>
          <ul >
            <li >
              
              <a href="https://tailwindcss.com"> First Link</a>
            </li>
            <li >
              
               <a href="https://tailwindcss.com"> Second Link</a>
            </li>
            <li >
              
               <a href="https://tailwindcss.com"> Third Link</a>
            </li>
          </ul>
          </div>
       
      </div>
    </div>
  </div>
</div>

  • Related