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