How do you make Scroll center on the elements inside the container?

Asked

Viewed 399 times

7

Imagine that I have an image gallery that is inside a container. But each image in the gallery has a size according to the image:

inserir a descrição da imagem aqui

What I’d like to do is a snap, so that at the time of scroll at a certain point the target element goes to the opposite of the container according to this gif. Note that at a certain point the scroll means that "automatically" centers on the next element!

inserir a descrição da imagem aqui

Is there any way to do this only with CSS?

  • Good question. Just one question, do you want the image closer to the center scroll or in the middle of dragging of scroll?

  • @fernandosavio Actually I don’t want something specific or anything, I want that when the image approaches the center it kind of centralizes automatically, it doesn’t need to be when release the scroll no

  • I’m thinking about how to do this with JS, with CSS will be very unlikely. hahaha

  • @fernandosavio vc deveria frequentar mais o Chat da comunidade :) https://chat.stackexchange.com/rooms/11910/overflow

  • For those who want to explore: https://developers.google.com/web/updates/2018/07/css-scroll-snap

  • @Sam I’m here waiting for someone with good will... :)

  • 1

    I didn’t know these properties, but it’s interesting. If someone answers I’ll learn :D

Show 2 more comments

1 answer

1


Yes! You need to give the container the rule scroll-snap-type: x mandatory, in the case of the horizontal scroll, and to the children give the rules scroll-snap-align: center.

Now to the most complete answer. As for the container you must pass two parameters:

1) As for accuracy, the snap can be 'Mandatory' or 'Proximity'. In the first case, the snap will be rigorous and in the second the snap will work only if the element is close to position.

2) As for the axis, the snap can occur on the x, y or 'Both' axes (both).

You can also create a padding applicable to the snap only. For example, if you want items to line up on the left, but they don’t touch the left side, you could add the rule scroll-padding: 10px.

Examples:

#container{
    scroll-snap-type: x mandatory;
}
#container{
    scroll-snap-type: both proximity;
    scroll-padding: 10px;
}

As to the elements:

You should say if you want to align them at the beginning, center or end with the rule scroll-snap-align in "start", "center" or "end". Also, similarly to the container padding, you can use scroll-margin to set applicable margins for scroll only.

Examples:

#container>.element{
    scroll-snap-align: center;
}
#container>.element{
    scroll-snap-align: start;
    scroll-margin-left: 50px;
}

Source: https://developers.google.com/web/updates/2018/07/css-scroll-snap

Browser other questions tagged

You are not signed in. Login or sign up in order to post.