🦁
css コンテナークエリー container-type: inline-size;
コンテナークエリーを使ってできること
指定した祖先要素を基準に、要素のサイズ指定ができる。
他の単位の場合、
- パーセント(%)の場合:親要素のサイズによって、要素のサイズが決まる。
- 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
@container
ルール は使わなくても cq* 系単位って使えるのでしたでしょうか……?公式のサンプルでも
@container
外でフォールバックを設定する感じですし、できない気もするのですが……?→ できた!
できるやんけ! 暗黙で
:root
が container じゃん!!!ちゃんと仕様書に書いてあった
つまり「適切なクエリ コンテナが利用できない場合は、その軸の小さいビューポート サイズを使用します。」であるので 実質
:root
が size コンテナ扱いぽい。お騒がせしました。