- CSS-Only Carousel
- Comments
- Keep up to date on web dev
- Как создать карусель, используя только HTML и CSS без JavaScript!
- Item 1
- Item 2
- Item 3
- 15 Best CSS Carousels 2023
- 1. CSS-Tricks Card Carousel
- 2. 3D Carousel Rotating
- 3. CSS Carousel – Pure CSS Carousels
- 4. CSS Variables 3D Carousel (No JS)
- 5. CSS Carousel With Keyboard Controls
- 6. Pure CSS Carousel
- 7. Multidirectional Email Carousel
- 8. A CSS-Only Carousel Slider
- 9. Playlist Carousel – CSS Only
- 10. [CSS] Infinite Autoplay Carousel
- 11. Pure CSS Carousel
- 12. Pure CSS Carousel With Thumbnails
- 13. CSS Vertical Carousel Animation
- 14. Very Simple Pure CSS Carousel
- 15. Responsive Sliding Carousel
CSS-Only Carousel
Christian Schaefer has taken it a little further with next and previous buttons, plus an auto-play feature that stops playing once interaction starts.
About that auto-play thing — it’s a bonafide CSS trick:
- First I slowly offset the scroll snap points to the right, making the scroll area follow along due to being snapped to them.
- After having scrolled the width of a whole slide, I deactivate the snapping. The scroll area is now untied from the scroll snap points.
- Now I let the scroll snap points jump back to their initial positions without them “snap-dragging” the scroll area back with them
- Then I re-engage the snapping which now lets the scroll area snap to a different snap point 🤯
JavaScript-powered slideshows (e.g. with Flickty) can be real nice, too. There is just something neat about getting it done with so little code.
And speaking of how far we can get with HTML and CSS, here are a few related takes on image carousels and galleries.
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
I tried it out in React and for some reason the buttons don’t work. Anybody know why? https://codesandbox.io/s/dreamy-currying-mmic6
I also noticed the scrollbar for the first example looking somewhat ugly in Firefox (Windows), and the second example not working when clicking the big buttons in Firefox (Windows).
Is there a modern way peeps are preventing the “anchor jump” – for example I’m using this in the middle of a page and don’t want the slider jumping to the top each time a user clicks on the slide nav (using your first method)…
Same here. I don’t mind jumping to some ID point on the page, but my use requires some text remains visible above the Carousel. Further, instead of the dots at bottom, I intend to put (CSS) text-based buttons ABOVE the carousel. I can kludge them to that position by changing the “bottom” spec to a “top” negative number, but clicking to a carousel page scrolls it to the top of the window, making everything above it disappear. In answer to others’ question, the repositioning is because the code changes frames by an jump to another specified anchor. But the jump not only moves the view sideways, it moves it to the top of the browser window. AFAIK, there’s no way to jump only sideways. Currently I’m playing with various position settings, but prospects don’t seem good, and I consider negative positioning always to be a kludge.
2.5 years late to the party, but I found a solution on this site.
https://markus.oberlehner.net/blog/super-simple-progressively-enhanced-carousel-with-css-scroll-snap/ The author uses a JS event listener to prevent the jumping. Worked like a charm for me.
Hi! I am trying to use the CSS-only Carousel you have posted here, and I can’t figure out how to get rid of the number that is on top of it, like the “1”, “2”, etc. How do I get rid of those? I am putting images in the background of the carousel, and the numbers look bad on top of it.
Hi Katie, I had this too and it was because I hadn’t included this section that removes the list style –
It’s a counter that is incremented, inserted by a content value. I think you can get rid of it simply by replacing the value with a null string. But if you don’t need the counter, it might be better to get rid of the code that defines it, along with omitting this content line.
Below, I’ve comment out the original, and replaced it: .carousel__slide:before /* content: counter(item); */
content: “” ;
Hi, I am curious how could you make the buttons active, depending on which one you pressed or which screen you swiped to?
I’d like to adapt a version of this to add a heading carousel to my website at https://www.stevesims.com. Can I ask how you hide the navigation arrows please?
The side buttons are defined in this part of the CSS code. Deleting this style makes them disappear. I haven’t tested to see if that area is still hot. Myself, I want the Previous/Next buttons, but they should be moved outside the slide area or made transparent (depending on the carousel’s placement in the overall page), so they don’t obscure content, which might be text or an important image detail. .carousel::before,
.carousel::after content: ”;
z-index: 1;
background-color: #333;
background-size: 1.5rem 1.5rem;
background-repeat: no-repeat;
background-position: center center;
color: #fff;
font-size: 2.5rem;
line-height: 4rem;
text-align: center;
pointer-events: none;
>
Hi, I used the CSS-only version and everything is OK except, when I place carousel on css grid. Every when I click on any control button, page focus on carousel (scrolls the page down and hide the top menu). How can I prevent these focus?
There’s a bug in Christian Schaefer’s carousel – when you traverse to the last image in the carousel, and then back to the first, the next button does not work. Any idea on how to prevent that?
I tried the two CSS-only carousels. Everytime a #jump-link is pressed, besides doing the intended it also jumps the box to the top of the page. Not sure what is causing this behavior. Kindly help me prevent this. Link for reference: https://www.hotlink.com/page/SIY00WE7CKD6/INOYHMTDX1IM Also in the auto-slide the next button does not work at first until some other button is used.
I like that Christian Schaefer’s is CSS only, and I want the side scroll buttons. And the autoscroll is interesting, as in some situations it can clue the user that changing is possible. But that’s pretty obvioius from the side buttons and if the bottom buttons are made into text buttons at top. (See another of my comments re that.) But two issues: 1. It doesn’t really demonstrate the range of content, as it just moves the first slide back into place. 2. Autoscroll pauses only on click or hover. If user moves cursor away, it resumes, and that’s REALLY annoying. So how do we omit autoscrolling altogether? I’m afraid I don’t understand the explanation enough to revised it except trial and error.
Keep up to date on web dev
with our hand-crafted newsletter
DigitalOcean
Как создать карусель, используя только HTML и CSS без JavaScript!
В последнее время мы работали над сайтом, который использует CMS, что немного ограничивает. Мы можем добавить свой собственный HTML и CSS на сайт, но не JavaScript.
В проектах, с которыми мы работали, была карусель. У нас были идеи о том, как мы можем сделать эту работу, используя CSS-анимации и transform property, но это дало бы карусель, прокручивающуюся автоматически и не разрешающую пользовательский ввод, что мам не было нужно. Немного подумав, мы приняли решение, которое использует абсолютное позиционирование и :target псевдо-селектор для изменения z-index и opacity нашей карусели, чтобы циклировать через них.
Структура нашей карусели выглядит примерно так: у нас есть главный div.carousel-wrapper, который дает нашей карусели размер. Внутри нашей оболочки, у нас есть span.hidden-target элементы с уникальными идентификаторами, которые действуют в качестве мишеней для наших пунктов управления карусели и div.carousel-item элементов, которые содержат контент каждого из пунктов карусели.
Каждый из div.carousel-item элементов будет иметь контент, и две ссылки, a.arrow-prev и a.arrow-next, который мы используем для цикла между элементами карусели.
Потому что наши отдельные элементы карусели будут position: absolute (мы можем сложить их на вершине друг друга), мы должны установить высоту div.carousel-wrapper вручную. Мы собираемся попытаться разгрузить CSS к нашей внешней таблицы стилей, но некоторые из пунктов мы должны будем написать, чтобы сделать нашу карусель используемой и масштабируемой.
Мы также используем CSS, чтобы установить фоновое изображение из двух наших div.carousel-item элементов, чтобы сделать их более яркими, но мы оставим это ниже, чтобы наша разметка была более читаемой.
Item 1
Content goes here.
Item 2
Content goes here.
Item 3
Content goes here.
Вот и весь HTML. Он удивительно легкий. В CSS (SCSS, в данном случае), вот где происходит волшебство.
У вас есть карусель, которая полностью функциональна и на 100% состоит из HTML и CSS! Мы создали карусель с тремя элементами, но вы можете продолжать добавлять элементы, убедитесь, что вы добавляете больше целевых элементов, и связываете ваши ссылки правильно.
/* Here's where our carousel begins, with the main wrapper being relatively positioned, so that our absolutely positioned items are in the right place. */ .carousel-wrapper < position: relative; /* Our absolutely positioned carousel items span the width and height of its parent. We're making them transparent by default so that they fade in when we cycle through them using the arrow links. */ .carousel-item < position: absolute; top: 0; bottom: 0; left: 0; right: 0; padding: 25px 50px; opacity: 0; transition: all 0.5s ease-in-out; /* Did you notice the 50px left, right padding up above? It's so we can position our arrow links! Each one will be 50px wide. Also, I'm using empty links with a background image so that the links look like arrows. Make sure you swap out that URL with an actual URL so that your arrow links aren't just transparent rectangles. */ .arrow < position: absolute; top: 0; display: block; width: 50px; height: 100%; -webkit-tap-highlight-color: rgba(0,0,0,0); background: url("/carousel-arrow-dark.png") 50% 50% / 20px no-repeat; /* Let's put our arrow to go back on the left. */ &.arrow-prev < left: 0; >/* And our arrow to go forward on the right. Since I'm using the same arrow image for both my arrows, I'm rotating this one by 180 degrees so that it points in the right direction */ &.arrow-next < right: 0; -webkit-transform: rotate(180deg); transform: rotate(180deg); >> /* I really like how these carousel items look on a dark image background, so if a .carousel-item div has the class 'light', we'll make its text color white, and use a white arrow instad of a dark gray one. Again, make sure this arrow image exists somewhere */ &.light < color: white; .arrow < background: url("/carousel-arrow-light.png") 50% 50% / 20px no-repeat; >> /* Let's use using some media queries to resize the arrows on smaller devices.*/ @media (max-width: 480px) < .arrow, &.light .arrow < background-size: 10px; background-position: 10px 50%; >> > /* Let's set our jump link targets display: none; so that we're not making the browser jump to the top of the carousel whenever a user clicks on one of our arrow links. This attribute selector will target any element whose id starts with 'target-item'. */ [id^="target-item"] < display: none; >/* So, up above we made all our carousel items transparent, which means that on page-load, we'd have a big empty box where our carousel should be. Let's set our first item's opacity to 1 so that it displays instead. Also, we're setting its z-index to 2, so that it's positioned on top of the other carousel items. */ .item-1 < z-index: 2; opacity: 1; >/* But we don't want the first item to ALAWYS be opacity: 1; otherwise it would peek through when cycling between items two and above. */ *:target ~ .item-1 < opacity: 0; >/* . but if #target-item-1 is targeted, well we do want the first item to show up, so we're selecting it with the ~ sibling selector and setting its opacity to 1 again :-) */ #target-item-1:target ~ .item-1 < opacity: 1; >/* If any other target-item-# is targeted, let's select it using the sibling selector, make it fade in, and place it on top of the pile using z-index: 3. Here's where you'd add more target items if your carousel has more than three items. It might be worth adding like 10 items right off the bat. */ #target-item-2:target ~ .item-2, #target-item-3:target ~ .item-3 < z-index: 3; opacity: 1; >>15 Best CSS Carousels 2023
If you’re looking for the perfect way to put a creative CSS carousels on your site, you’re at the right place.
While you’re at it, why not add a sleek look to an interesting look? Today we are going to try to create a list of the best CSS carousels with animated, simple, elegant and more options.
Below is a link to each demo and code piece. Whether you want to start with your own design or you are looking for a fully finished carousels, you have it all.
So undoubtedly let’s get to the list.
1. CSS-Tricks Card Carousel
CSS-Tricks Card Carousel
Made By: William Goldsworthy2. 3D Carousel Rotating
3D Carousel Rotating
Made By: Claudiu Lazar3. CSS Carousel – Pure CSS Carousels
CSS Carousel – Pure CSS Carousels
Made By: Jhey4. CSS Variables 3D Carousel (No JS)
CSS Variables 3D Carousel (No JS)
Made By: Chris Neale5. CSS Carousel With Keyboard Controls
CSS Carousel With Keyboard Controls
Made By: David Lewis6. Pure CSS Carousel
Pure CSS Carousel
Made By: Olivier PASCAL7. Multidirectional Email Carousel
Multidirectional Email Carousel
Made By: Gary Wesolowski8. A CSS-Only Carousel Slider
A CSS-Only Carousel Slider
Made By: Christian Schaefer9. Playlist Carousel – CSS Only
Playlist Carousel – CSS Only
Made By: Aybüke Ceylan10. [CSS] Infinite Autoplay Carousel
[CSS] Infinite Autoplay Carousel
Made By: Jack Oliver11. Pure CSS Carousel
Pure CSS Carousel
Made By: TianyiLi12. Pure CSS Carousel With Thumbnails
Pure CSS Carousel With Thumbnails
Made By: Ronny Siikaluoma13. CSS Vertical Carousel Animation
CSS Vertical Carousel Animation
Made By: Aija14. Very Simple Pure CSS Carousel
Very Simple Pure CSS Carousel
Made By: Ben Evans15. Responsive Sliding Carousel
Responsive Sliding Carousel (CSS Animation Journey Collection)
Made By: januaryofmine