How to create CSS carousel (slider)

Milos Jankovic / 3 years / No Comments

Today, almost all websites have some kind of carousel (slider) and for that usually use some open source JavaScript library (like bxSlider or slick), which require usage of some other JavaScript library (like jQuery). In recent times, Google announced that more users use their mobile phones than desktop computers for search. That means higher probability that users are on the move and they don’t have fast and stable internet connection.

In that sense, websites need to load fast, without many external libraries which will slow down loading and block page rendering. Using two external libraries (which are about 120 KB) for creating carousel is demanding, so we will show you how to create carousel just with (S)CSS.

HTML

Code looks the same as one which you write when you use JS carousel, with addition of <input type=”radio”>. It is important to have input field for every slide with unique ID which needs to be connected with label.

SCSS

We will show here just important parts, whole SCSS is available on our GitHub repository.

Defining options (number of slides and transition speed in seconds):

This part is very important although is hidden, because checked input controls which slide is shown.

Labels are our carousel navigation which could be styled nicely and which toggles checked input field.

This code put all slides in one row and hides all inactive slides.

Main trick is in use of :checked pseudo class which refers to active slide and ~ (tilde sign) which refers to sibling elements. Thanks to this we are able to mark active navigation point and to move slides.

We used SCSS to create carousel and all what we need is just to edit number of slides, everything else will be done automaticaly during compile process.

Pros

  • Without usage of large external libraries
  • Save bandwidth and faster website loading

Cons

  • Unlike JS carousel which itself recognize number of slides, in CSS carousel developer must define number of slides.

Browser compatibility

Chrome Safari Firefox Opera IE / Edge Android iOS
Any 3.2+ 4+ 11.5+ 10+ Any Any