2

I have the following CSS:

:root {
    --some-number: 0;
}

.header-nav {
    container: header-nav-container / size;
}

@container header-nav-container (width < calc(400px + (var(--some-number) * 100px))) {
    .header-nav-menu__label {
        display: none;
    }
}

The code above, and specifically the dynamic width calculation doesn't seem to work as expected. If I replace the calc() above with simply 400px the container query works fine, but of course it's not dynamic anymore.

I tested the width calculation separately by setting it on the width property of another element, and the calculation itself seems to work fine, even when the some-number property increases.

What am I missing? Can we not use calc() inside container queries?

4
  • you cannot use calc() inside media query (or container query) Commented Feb 27, 2023 at 19:51
  • @TemaniAfif for media queries it seems to be browser-dependent, doesn't seem to be a straight no: stackoverflow.com/a/23675934/134120 Given that container queries are brand new, maybe one can hope? :) Commented Feb 27, 2023 at 20:02
  • I meant CSS variables not calc(). calc() may work with static values but with variables I don't think so because we cannot resolve it. Commented Feb 27, 2023 at 20:09
  • @TemaniAfif looks like you're right. Oh well, I'll have to find another way then... Commented Feb 27, 2023 at 23:34

1 Answer 1

0

It appears you can now use calc() inside media and container queries but you can't use variables (CSS custom properties).

I couldn't do exactly what I wanted:

@container (min-width: calc((2 * var(--item-width)) + var(--gap-between-items))) {
  /* ... */
}

But I confirmed that calc() does indeed work:

@container (min-width: calc((2 * 18rem) + 2rem)) {
  /* ... */
}

Though not ideal, I was able to much more cleanly do what I wanted.

Sign up to request clarification or add additional context in comments.

1 Comment

That was already the case 2 years ago when I asked the question, you can read the comments above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.