- Instant help with your CSS coding problems

Access child elements in TailwindCSS

Question:
How to access child elements in TailwindCSS?
Answer:
<div class="p-10 [&>div]:pb-3">
Description:

If you want to access the direct children of an HTML element in TailwindCSS, you can easily do so using the arbitrary variants feature since version 3.1.

For example if you want to add extra padding to the bottom of each direct child div elements you can write this:

    <div class="[&>div]:pb-3">
      <div>
        <div>A-1</div>
        <div>A-2</div>
        <div>A-3</div>
      </div>
      <div>
        <div>B-1</div>
        <div>B-2</div>
        <div>B-3</div>
      </div>
      <div>
        <div>C-1</div>
        <div>C-2</div>
        <div>C-3</div>
      </div>
    </div>

And this will result an output:

Important: The space character is not allowed in the expression! Either you must write everything completely in one word, or use the underscore _ character instead of the space character.

Examples:

  • <div class="[& > div]:pb-3"> INVALID

  • <div class="[&>div]:pb-3"> VALID

  • <div class="[&_>_div]:pb-3"> VALID
 
 
Share "How to access child elements in TailwindCSS?"
Interesting things
OpanAi's ChatGPT