Skip to content

[css-conditional-5] Desugaring @if #12909

@andruud

Description

@andruud

With inline if() and revert-rule now in place, do we indeed1 have everything we need to add a useful block-if?

Just like how @container imposes an additional "late" (vs MQs) condition on rules, we could use similar behavior for @if:

@container (width > 800px) {
  .thing { font-size: 30px; }
}

The above effectively behaves as2:

.thing { font-size: if(container(width > 800px):30px; else:revert-rule); }

@if could work the same way:

@if style(--mode:pill) {
  .box { border-radius: 10px; }
}

Desugared:

.box { border-radius: if(style(--mode:pill):10px; else:revert-rule); }

Obviously it would work with nesting, so you can set a bunch of things conditionally in a nice way:

.box {
  @if style(--mode:pill) {
    border-radius: 10px;
    background-color: tomato;
    padding: 4px;
  }
}

This "inlinification" should answer questions about cycles (etc) automatically. I wouldn't expect implementations to literally perform this, of course. It's just a way of explaining the behavior from existing primitives.

Multiple levels of @if would desugar into a compound if-test:

@if style(--mode:pill) {
  @if style(--theme:dark) {
    .box { border-radius: 10px; }
  }
}

Desugared:

.box { border-radius: if(style(--mode:pill) and style(--theme:dark):10px; else:revert-rule); }

There might be a potential trap when using nesting, e.g. authors could reasonably expect the following if-test to branch off of <div class=box>'s variables, when in reality style(--mode:pill) gets evaluated against <div class=inner>'s variables:

.box {
  @if style(--mode:pill) {
    .inner { green: green; }
  }
}

However, this is similar to how different rules within a single @container rule can target totally different containers based on the element being matched.


Thoughts on this? E.g. @tabatkins, @LeaVerou?

Footnotes

  1. See Pave the cowpaths for block @if in https://github.com/w3c/csswg-drafts/issues/12806

  2. Using the proposed container() test from https://github.com/w3c/csswg-drafts/issues/12069.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions