Blaze Slider
Tutorial

Preventing Layout Shifts

Achieve zero CLS with CSS variables

Layout shifts happen when page elements move unexpectedly after initial render. They frustrate users and hurt your CLS score.

Most slider libraries cause this - the layout jumps when JavaScript initializes. Blaze Slider eliminates this with CSS variables.

The Problem

A slider showing 3 slides on desktop, 2 on mobile:

new BlazeSlider(el, {
  all: { slidesToShow: 3 },
  '(max-width: 500px)': { slidesToShow: 2 },
});

Without CSS configuration, the browser renders all slides stacked. When JavaScript runs, they suddenly snap into place. Toggle between these states to see the shift below

1
2
3
4

This shows how the slider looks before JavaScript runs.

The Fix

Set the same values in CSS. The browser renders the correct layout before JavaScript loads.

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

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

CSS variables must be on the .blaze-slider element.

Now the layout is stable:

1
2
3
4

This shows how the slider looks before JavaScript runs. No layout shift - CSS variables keep it stable.

CSS Variables

VariableDescription
--slides-to-showNumber of visible slides
--slide-gapGap between slides (e.g. 16px)

Keep CSS and JavaScript values in sync.

Example

.my-slider.blaze-slider {
  --slides-to-show: 3; 
  --slide-gap: 16px; 
}

@media (max-width: 500px) {
  .my-slider.blaze-slider {
    --slides-to-show: 2; 
  }
}
new BlazeSlider(document.querySelector('.my-slider'), {
  all: {
    slidesToShow: 3, 
    slideGap: '16px', 
  },
  '(max-width: 500px)': {
    slidesToShow: 2, 
  },
});
1
2
3
4

On this page