CSS - animations for a carousel of multiple items

Viewed 216

I created a multiple items carousel, and I want to add sliding animations to it.
For example, on click right, I want that the displayed items will fade out from right to left, and the new items will replace them from right to left as well (but the new ones will come from out of the screen)

I'm using CSS grid for the layout of the items:
display: grid; grid-template-columns: repeat(4, 2.5rem); gap: 1rem;
and I'm hiding the items that are not relevant to the displayed slide using visibility: hidden.

Here is an abstract example of the carousel - https://jsfiddle.net/dehxzLn6/48/

As you can see, the visibility: hidden property is hiding the elements, but they still taking space, so it's another issue that I need to solve.

I would be very happy if you could help me figure out how to add animations to a carousel like this.
thanks!

enter image description here enter image description here

1 Answers

As answered before me, "visibility: hidden" elements take up space on the page, so you can use the display property instead.

Other option is to 'stack' the items in position. There's a few ways to it, like the position property, but you're using grid, so you can use grid-areas.

As for the animation, you can use the opacity property and transition it. And to get the effect you want, you can add a delay according to the position...

.items-wrapper {
  display: grid;
  grid-template-areas:
    "a b c d"
    "e f g h";
  gap: 1rem;
  margin: auto 0;

  .item {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: 0px 4px 4px rgba(46, 37, 37, 0.15), 0px 0px 10px 1px rgba(203, 205, 208, 0.3);
    border-radius: 4px;
    padding: 0.5rem;
    height: 2.5rem;
    transition: opacity 0.8s calc(var(--delay) + var(--delayOffset, 0s));

    &.is-hidden {
      opacity: 0;
      --delayOffset: -0.8s;
    }

    &.pos0 { grid-area: a; --delay: 0.8s; }
    &.pos1 { grid-area: b; --delay: 0.9s; }
    &.pos2 { grid-area: c; --delay: 1.0s; }
    &.pos3 { grid-area: d; --delay: 1.1s; }
    &.pos4 { grid-area: e; --delay: 1.2s; }
    &.pos5 { grid-area: f; --delay: 1.3s; }
    &.pos6 { grid-area: g; --delay: 1.4s; }
    &.pos7 { grid-area: h; --delay: 1.5s; }
  }

Here's a simple example: https://jsfiddle.net/kbn1rw28/

Related