While working with CSS carousels, I needed a solution that could adapt the position of the scroll buttons to be either inside or outside based on the available space.
I'm using anchoring to pin the buttons wherever I want, and when they're outside, there's potential for them to be off screen or out of bounds.
The solution? #
Use calc()
inside the container query:
.carousel {
…
&::scroll-button(right),
&::scroll-button(left) {
position-area: var(--_outer);
}
/* inner positioned arrows when carousel
is full width of viewport or container
note: 120px is both arrows plus their margins
*/
@container (inline-size >= calc(100cqi - 120px)) {
&::scroll-button(right),
&::scroll-button(left) {
position-area: var(--_inner);
}
}
}
The default anchored position is outside the carousel, but when the carousel (inline-size
) is as wide (>=
) as it's nearest container 100cqi
(which might be the viewport), then move the arrows safely inside.
calc(100cqi - 120px)
is the size of the carousel's nearest container minus the combined size of the scroll buttons.
Pretty sweet how much this can do in one line of CSS.