🦁

css コンテナークエリー container-type: inline-size;

2025/03/27に公開3

コンテナークエリーを使ってできること

指定した祖先要素を基準に、要素のサイズ指定ができる。

他の単位の場合、

  • パーセント(%)の場合:親要素のサイズによって、要素のサイズが決まる。
  • vwの場合:ブラウザの幅によって、要素の幅が決まる。

それに対してコンテナークエリーを使う場合、

  • cqwの場合:指定した祖先要素の幅によって、要素の幅が決まる。

ユースケース

例えば、親要素の幅が0のとき、子要素の幅を%で指定した場合、0になる。

<div class="parents">
    <div class="child">
      <div class="grandchild -percent"></div>
    </div>
</div>
  .parents {
    position: relative;
    width: 100%;
    height: 600px;
    background-color: red;
  }

  .child {
    position: absolute;
    z-index: 2;
    right: 0;
    width: 0;
  }

  .grandchild {
    position: absolute;

    &.-percent {
      left: 0;
      width: 50%;
      height: 600px;
      background-color: blue;
    }
  }

コンテナークエリーを使うと、、

指定したい祖先要素に

 container-type: inline-size;

をつける。
単位はcqwを使う。

<div class="parents">
    <div class="child">
      <div class="grandchild -cqw"></div>
    </div>
</div>
  .parents {
    position: relative;
    width: 100%;
    height: 600px;
    background-color: red;
    container-type: inline-size;
  }

  .child {
    position: absolute;
    z-index: 2;
    right: 0;
    width: 0;
  }

  .grandchild {
    position: absolute;

    &.-cqw {
      z-index: 2;
      right: 0;
      width: 50cqw;
      height: 600px;
      background-color: green;
    }
  }

こうすることで、position: absolute;を使った要素にも幅をもたせることができます。

Discussion

junerjuner

コンテナークエリーを使うと

@container ルール は使わなくても cq* 系単位って使えるのでしたでしょうか……?

公式のサンプルでも @container 外でフォールバックを設定する感じですし、できない気もするのですが……?
→ できた!

/* The fallback value does not rely on containment */
h2 { font-size: 1.2em; }

@container (inline-size >= 0px) {
  /* only applies when an inline-size container is available */
  h2 { font-size: calc(1.2em + 1cqi); }
}

https://drafts.csswg.org/css-conditional-5/#example-a4252068

junerjuner

できるやんけ! 暗黙で :root が container じゃん!!!

main {
  &.type-1 {
    padding: 1em;
    height: calc(50vh - 1em);
    container-type: size;
    .main-1 {
      /* ↓ 直近のコンテナは .type-1 な為そこから計算 */
      height: 25cqh;
    }
    /* ↓ .type-1 が コンテナな為、利く */
    @container (block-size >= 0) {
      .main-2 {
        height: 25cqh;
      }
    }
  }
  &.type-2 {
    padding: 1em;
    height: calc(50vh - 1em);
    .main-3 {
      /* ↓直近のコンテナは :root な為そこから計算 */
      height: 25cqh;
    }
    /* ↓ .type-2 が コンテナでない為、利かない */
    @container (block-size >= 0) {
      .main-4 {
        height: 25cqh;
      }
    }
  }
}
junerjuner

ちゃんと仕様書に書いてあった

For each element, container query length units are evaluated as container size queries on the relevant axis (or axes) described by the unit. The query container for each axis is the nearest ancestor container that accepts container size queries on that axis. If no eligible query container is available, then use the small viewport size for that axis.

https://drafts.csswg.org/css-conditional-5/#container-lengths

つまり「適切なクエリ コンテナが利用できない場合は、その軸の小さいビューポート サイズを使用します。」であるので 実質 :root が size コンテナ扱いぽい。

お騒がせしました。