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

7

Imagine that I have an image gallery that is inside a container . However each image in the gallery has a size as the image:

WhatIwouldliketodoisasnap,sothatatthetimeofscrollatsomepointthetargetelementgoestocontainercontrolasthisgif.Noticethatatacertainpointthescrollmeansthatit"automatically" centers on the next element!

Is there any way to do this with CSS only?     

asked by anonymous 25.09.2018 / 20:45

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 the children give the scroll-snap-align: center rules.

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

1) As for rigor, the snap can be 'mandatory' or 'proximity'. In the first case, the snap will be strict and in the second the snap will only work if the element is close to the position.

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

You can also create a padding that applies only to the snap. For example, if you want items to align to the left, but do not 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 for elements :

You should say whether you want to align them by start, center, or end with the scroll-snap-align rule in "start", "center" or "end". In addition, similarly to container padding, you can use scroll-margin to set margins applicable only to scroll.

Examples:

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

Source: link

    
30.09.2018 / 02:40