ReasonJun

Tailwindcss : Carousel Dynamic width control 본문

Frontend/Tailwindcss

Tailwindcss : Carousel Dynamic width control

ReasonJun 2024. 10. 15. 12:16
728x90

Problem : 

I wrote the Carousel code as shown below. I wanted the width of the carousel to be responsive to the screen size, but it wasn't, so I specified a maximum width for each screen size : "max-w-sm xs:max-w-md sm:max-w-xl md:max-w-3xl lg:max-w-5xl xl:max-w-7xl". It adjusted well to the screen size, but the problem was that there were often black spaces.

 

<div
        className="flex overflow-x-scroll overscroll-x-auto scroll-smooth py-12 [scrollbar-width:none]"
        ref={carouselRef}
        onScroll={checkScrollability}
      >
        <div className="mx-auto flex flex-row justify-start gap-3 pl-4 sm:gap-4">
          {items.map((item, index) => (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{
                opacity: 1,
                y: 0,
                transition: {
                  duration: 0.5,
                  delay: 0.1 * index,
                  ease: "easeOut",
                },
              }}
              key={`card${index}`}
              className="rounded-3xl md:last:pr-[calc(50%-1rem)] lg:last:pr-[33%]"
            >
              {item}
            </motion.div>
          ))}
        </div>
      </div>

Why : 

 

width doesn't move responsively in a carousel for the following reasons : 

 

 

  • Fixed width on items: The code doesn't show how the individual items are styled. If the items have a fixed width, they won't resize responsively.
  • Overflow behavior: The carousel is set to overflow-x-scroll, which allows horizontal scrolling but doesn't automatically resize content.

 

Solution : 

I wrapped this code and it worked.

 

 

<div className="relative w-[90vw] max-w-7xl">

 

 

Why : 

 

  • w-[90vw]: This sets the width to 90% of the viewport width, which makes the container responsive to the screen size.
  • max-w-7xl: This sets a maximum width (in Tailwind, this is typically 1280px), preventing the carousel from becoming too wide on large screens.
  • relative: This establishes a new positioning context for absolute elements inside the carousel (like the navigation buttons).

 

728x90

'Frontend > Tailwindcss' 카테고리의 다른 글

Tailwindcss : justify-center and Accordian height Problem  (0) 2024.02.21
Tailwindcss : twMerge, clsx  (0) 2023.11.01
Comments