wayoh22
wayoh22

Reputation: 176

How to create alternating vertical timeline with Tailwind & CSS

I'm trying to create a timeline that has the odd children on the left of the timeline and the even children on the right in a react app. Image to demonstrate: Timeline

I think the problem I'm having is that I'm using it within a loop. So for every item in the loop I want it to display to the left or right depending if the child is an even or odd. I have tried using the variant utility with Tailwind for odd and even but I haven't been able to configure it. I have also tried using simple CSS but can't get it to alternate.

/project.js

return (
        <div className="antialiased text-gray-800 bg-gray-100">
            <div className="container relative flex flex-col px-6 mx-auto space-y-8">
                <div className="absolute inset-0 z-0 w-2 h-full bg-white shadow-md left-17 md:mx-auto md:right-0 md:left-0"></div>
                {projectData && projectData.map((project, index)=> (
                <div className="relative z-10">
                    <img src={project.mainImage.asset.url} alt={project.mainImage.alt} className="timeline-img" />
                    <div id="container" className="timeline-container">
                        <div id="pointer" className="timeline-pointer" aria-hidden="true"></div>
                        <div className="p-6 bg-white rounded-md shadow-md">
                            <p className="pt-1">{project.description}</p>
                        </div>
                    </div>
                </div>    
                ))}
            </div>
        </div>
    )

index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

#container:nth-child(odd) {
    @apply timeline-container-left timeline-container;
}

#pointer:nth-child(odd) {
    @apply timeline-pointer timeline-pointer-left;
}

@layer components {
    .timeline-img {
        @apply object-cover w-24 h-24 border-4 border-white rounded-full shadow-md xs:absolute md:mx-auto md:left-0 md:right-0;
    }
    .timeline-container {
        @apply relative pt-2 xs:pl-28 xs:pt-0 md:w-1/2 md:ml-auto md:pl-16;
    }
    .timeline-container-left {
        @apply md:ml-0 md:mr-auto md:pl-0 md:pr-16;
    }
    .timeline-pointer {
        @apply absolute inset-0 w-4 h-4 transform rotate-45 bg-white left-10 xs:top-11 xs:left-26 md:left-14;
    }
    .timeline-pointer-left {
        @apply md:left-auto md:right-14;
    }
}

I just need to apply

@apply timeline-container-left

and

@apply timeline-pointer-left

onto the container and pointer divs

Upvotes: 0

Views: 1545

Answers (1)

Vincenzo
Vincenzo

Reputation: 433

I think you could reference the index of each item and use it in a ternary operator inside the className where if index modulo 2 returns 0 it means it is an even number, like so <div className={`${index % 2 == 0 ? "ml-auto" : "mr-auto" }`}>

Upvotes: 1

Related Questions