Skip to main content

Fix Layout shifts

If you are not familiar with the term "layout shift", Refer to web.dev/cls to understand what is layout shift, and how it affects the end-user of your website and CLS metric of your website.

Unlike other libraries, blaze-slider provides an easy way to fix the layout shifts caused by slider initialization.

Let's first understand what happens if you don't fix the layout shift.

Let's say that you want to show 3 slides in the slider on desktop and 2 slides on mobile view, and you are using the below-shown code to initialize the slider

Example

<div className="blaze-slider foo-slider">
<div className="blaze-container">
<div className="blaze-track-container">
<div className="blaze-track">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
</div>
</div>
</div>
new BlazeSlider(el, {
all: {
slidesToShow: 3,
},
'(max-width: 500px)': {
slidesToShow: 2,
},
})
1
2
3
4

Use the buttons "Before JS Execution" and "After JS Execution" Buttons to see how the layout shifts when JavaScript is executed and slider is initialized.

This happens because until JavaScript runs, the slider's layout is rendered using only CSS, and when the JavaScript runs it initializes the slider using the configuration you gave and changes the layout accordingly

But Our goal is to have the same layout Before and After JavaScript runs - to avoid layout shifts.

To do this, the slider must "know" about the configuration before JavaScript runs. And we can achieve this by providing the layout configuration in using css variables in css file.

BlazeSlider uses CSS variables, two of which are --slides-to-show, --slide-gap which are responsible for the layout. So to avoid layout shift, you must configure these 2 css variables in CSS with same values you are configuring in JS.

Example

To target our slider in CSS, we have added one more class foo-slider in HTML above, so we can use that class for targetting the slider and configure the CSS variables.

note

CSS varibles must be configured on .blaze-slider selector.

.foo-slider.blaze-slider {
--slides-to-show: 3;
}

@media (max-width: 500px) {
.foo-slider.blaze-slider {
--slides-to-show: 2;
}
}

By adding this CSS, we have successfully removed the layout shifts and created a stable UI that looks exactly the same before and after JavaScript is executed

1
2
3
4