Search code examples
vue.jstailwind-css

Tailwind - Apply Justify-Between if multiple children else Justify-End


I have a Vuejs component with a flex div containing a slot. As I do not know how many elements will be in the slot, I would like the content to be 'justify-between' if there is more than 1 element, otherwise 'justify-end' (right aligned). Is that possible using just CSS in TailwindCss?

  <div class="flex justify-between gap-2 select-none" >
    <div class="px-5 py-3 font-extrabold bg-slate-400">justify-between</div>
    <div class="px-5 py-3 font-extrabold bg-slate-400">if 2+ divs</div>
    <div class="px-5 py-3 font-extrabold bg-red-400">justify-end if 1 div</div>
  </div>

Justify-between if 2+ divs otherwise justify-end


Solution

  • Using Tailwind 3.4.4+, you can put conditional arbitrary selectors on the parent flex div using the :has() and :not() variants with the :only-child selector. It would be great to see a more streamlined way to do this but it works.

     <script src="https://cdn.tailwindcss.com"></script>
    
    <div class="border border-red-500 m-5 p-5"> 
    
      <div class="flex justify-between [&:has(:only-child)]:justify-end gap-2 select-none" >
        <div class="px-5 py-3 font-extrabold bg-slate-400">justify-between</div>
        <div class="px-5 py-3 font-extrabold bg-slate-400">if 2+ divs</div>
        <div class="px-5 py-3 font-extrabold bg-red-400">justify-end if 1 div</div>
      </div>
     
    </div>