Search code examples
responsive-designwidthtailwind-css

tailwindcss 50% width all div


<div class="flex overflow-y-auto">
  <div class="w-1/2 bg-red-500 ">w-first</div>
  <div class="w-1/2 bg-blue-500">w-second</div>
  <div class="w-1/2 bg-green-500">w-third</div>
  <div class="w-1/2 bg-yellow-500">w-fourth</div>
</div>

I wants 2 div per row, i can use a div wrap to (first, second) div, then use w-1/2 that times it works fine. but if i have unlimited div its not possible to wrap all div in same time.


Solution

  • It looks like a perfect scenario for the grid layout.

    While flex is designed for one-dimensional layouts, for a two-dimensional layout like the one you have, grid would be a better fit.

    Switch the flex utility with the grid utility. Then, specify the number of columns by using grid-cols-2. This utility will limit the number of elements of each row to 2.

    You can read more about the grid-cols-{n} utility here.


    <div class="grid grid-cols-2 overflow-y-auto">
      <div class="bg-red-500">w-first</div>
      <div class="bg-blue-500">w-second</div>
      <div class="bg-green-500">w-third</div>
      <div class="bg-yellow-500">w-fourth</div>
    </div>
    

    Tailwind-Play

    image of the result