Search code examples
javascriptreactjscss-selectorstailwind-css

How to implement the last-child using Tailwind?


I have tried without success to implement the prefix last: as shown in the Tailwind CSS documentation. Can anyone point out what I am doing wrong? I cannot make this work.

{items.map((item, i) => {
  return (
    <li
      key={i.toString()}
      v-for="(item, i) in items"
      className="pb-sm xl:pb-md last:pb-0" // This is the problematic fellow!
    >
      <div className="grid grid-cols-12">
        <div className="col-start-2 col-span-10 md:col-start-2 md:col-span-8  pb-2 sm:pb-xs md:pb-xs lg:pb-xs xl:pb-0">
          <div className="serif text-h5 xl:text-h4 lg:text-h4 md:text-h4 leading-snug xl:leading-tight lg:leading-tight md:leading-snug">
            {item}
          </div>
        </div>
        <div className="col-start-2 col-span-10 sm:col-start-5 sm:col-span-6 md:col-start-5 md:col-span-6 lg:col-start-5 lg:col-span-6 xl:col-start-5 xl:col-span-3 pb-xs sm:pb-xs">
          <div className="text-p sm:text-p">{description[i]}</div>
        </div>
      </div>
    </li>
  )
})}

Solution

  • Not sure if you're using Tailwind v2.X or v1.X but you need to activate the variant for last. Here is a quote from the official v2 docs related page

    By default, the last-child variant is not enabled for any core plugins.

    I've tried to make an example for you on https://play.tailwindcss.com/ but it doesn't work there. Meanwhile, I spin a Vite VueJS repo with the latest version of TW and it's working perfectly.

    So, this in your tailwind.config.js should do the trick

    module.exports = {
      ...
      variants: {
        extend: {
          padding: ['last'],
        }
      },
      ...
    }
    

    v2's documentation is here and v1's is here.
    Beware, the variants >> extend is only available in the v2. If you're using v1, you can still override the whole padding variant manually, not a big deal.

    PS: Tailwind's team fixed the issue already, damn !