For the carousel we built so far, the width of each slide is fixed to 800px. This is unacceptable. We want our carousel to be responsive.
For our carousels to be responsive, we need to let our user’s browsers determine the width of each slide.
For this to happen, let’s change the 800px limit to 80vw. This means 80% of the browser’s viewport width.
/* Change this */.carousel { grid-template-columns: 3em 800px 3em;}
/* To this */.carousel { grid-template-columns: 3em 80vw 3em;}Here’s what you might see:
In this case, 80vw in my browser is larger than 800px. The second slide is set to 800px. It overlaps the first slide because of this.
We can no longer position slides with CSS. We need to position slides with JavaScript.
Positioning the slides with JavaScript
First, let’s remove slide positions we wrote in the CSS:
/* Remove these */.carousel__slide:nth-child(2) { left: 800px;}
.carousel__slide:nth-child(3) { left: 1600px;}From the previous lessons, we know these:
leftof second slide should be one slide’s width.leftof third slide should be two slide’s width.
We need to find the width of one slide first. We can get the width of one slide with getBoundingClientRect. In this case, Getting the width of the first slide is sufficient.
const rect = slides[0].getBoundingClientRect()console.log(rect)
We can get the width of one slide with the width property from getBoundingClientRect.
const rect = slides[0].getBoundingClientRect()const slideWidth = rect.width
console.log(slideWidth) // 936 (This may be a different number in your case. It depends on the width of your browser).You can shorten the code above slightly by chaining properties together.
const slideWidth = slides[0].getBoundingClientRect().widthNext, we want to position the slides with JavaScript.
- First slide’s
leftshould be0px - Second slide’s
leftshould beslideWidth - Third slide’s
leftshould be twoslideWidths
slides[0].style.left = '0px'slides[1].style.left = slideWidth + 'px'slides[2].style.left = slideWidth * 2 + 'px'To make the calculations consistent, you can substitute the above with this:
slides[0].style.left = slideWidth * 0 + 'px'slides[1].style.left = slideWidth * 1 + 'px'slides[2].style.left = slideWidth * 2 + 'px'Notice we can use the index of each slide to calculate the correct left value? Since you see this pattern now, let’s switch to a forEach loop to position the slides.
slides.forEach((slide, index) => { slide.style.left = slideWidth * index + 'px'})
That’s it!
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson