CSS Carousel - Navigation Buttons
Adding the ubiqitous < and > buttons, including all functionality and the “disabled” state when you reach the end of either direction, is all CSS, automatically handled by the browser, no JS required.
Demo
- Slide 1
- Slide 2
- Slide 3
- Slide 4
- Slide 5
- Slide 6
- Slide 7
- Slide 8
- Slide 9
- Slide 10
HTML
<!-- No special HTML required, just a list -->
<ul class="css-carousel">
<li>Slide 1</li>
<li>Slide 2</li>
<li>Slide 3</li>
<li>Slide 4</li>
<li>Slide 5</li>
<li>Slide 6</li>
<li>Slide 7</li>
<li>Slide 8</li>
<li>Slide 9</li>
<li>Slide 10</li>
</ul>CSS
/* Basic carousel CSS */
.css-carousel {
/* Resets for carousel appearance */
list-style: none;
padding: 0;
/* The only CSS necessary for a simple swiper Carousel */
display: flex;
overflow-inline: auto;
/* Prevents accidental page Back/Forward */
overscroll-behavior-inline: contain;
/* Confines the scrolling direction */
scroll-snap-type: inline mandatory;
/* Be nice to others */
@media (prefers-reduced-motion: no-preference) {
/* Makes the sliding a little smoother */
scroll-behavior: smooth;
}
li {
/* Make things look a little nicer */
min-width: 200px;
aspect-ratio: 1 / 1;
border: 1px solid;
place-content: center;
text-align: center;
}
/** Add navigation buttons **/
/* Optionally remove the scrollbar from the carousel container */
scrollbar-width: none;
/* Using Anchor Position to place the buttons. */
anchor-name: --css-carousel__adding-buttons;
/* Create both buttons, define anchor scope */
&::scroll-button(*) {
position: fixed;
position-anchor: --css-carousel__adding-buttons;
}
/* Position "Previous" button, add an arrow as content, and provide `alt` text */
&::scroll-button(inline-start) {
position-area: inline-start center;
content: "⬅" / "Scroll Left";
}
/* Position "Next" button, add an arrow as content, and provide `alt` text */
&::scroll-button(inline-end) {
position-area: inline-end center;
content: "⮕" / "Scroll Right";
}
}JS
No JS required.Baseline
CodePen
See the Pen on CodePen.