Text emphasized alt text example
My google avatar.1 min read

A powerful container query

css
3,580 views · 7 active

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.

am I reading right that the “`calc()` expression in an at-rule” part of this is the segment that has the *widest* support? wild caniuse.com/mdn-css_at-r...
Jonathan CaprellJonathan Caprell
wildly wide support indeed!
Adam ArgyleAdam Argyle
Do u think this might also be possible using overflow try fallbacks? Wild guess, just saw Kevin Powell talk about it the other day..
Nils BorgNils Borg
possibly, but i believe those are mostly focused around scrollports and not containers (for the auto flipping), so you'd be limited to overflow scenarios and not generic available space.
Adam ArgyleAdam Argyle

@argyleink@front-end.social If you need to do such weird stuff, perhaps you've tried to style too much. Go a few steps back and try to keep it simple, it'll most likely be a bandwidth and usability improvement as well.

tyiltyil