コンテナのorientation クエリ — ポートレート vs ランドスケープ
orientationコンテナ機能を使用して、コンテナが縦長(portrait)か横長(landscape)かに応じて異なるスタイルを適用します。
Advanced Patterns
詳細な説明
コンテナ orientation クエリ
コンテナクエリのorientation機能は、ビューポートのorientation メディア機能と同様に動作しますが、ビューポートではなくコンテナのディメンションに適用されます。
CSS
.panel {
container-type: size; /* orientationには'size'が必要 */
container-name: panel;
width: 100%;
height: 400px; /* サイズ包含に明示的な高さが必要 */
}
@container panel (orientation: landscape) {
.panel-layout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
}
}
@container panel (orientation: portrait) {
.panel-layout {
display: flex;
flex-direction: column;
gap: 1rem;
}
}
orientationの判定方法
- Landscape: コンテナ幅 >= コンテナ高さ
- Portrait: コンテナ高さ > コンテナ幅
要件
orientationは幅と高さの両方に依存するため、container-type: size(inline-sizeではなく)を使用する必要があります。コンテナには確定的な高さが必要です。
実践例:画像ギャラリー
.gallery-container {
container: gallery / size;
width: 100%;
height: 100%;
}
@container gallery (orientation: landscape) {
.gallery {
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(2, 1fr);
}
}
@container gallery (orientation: portrait) {
.gallery {
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(4, 1fr);
}
}
ギャラリーはランドスケープ方向ではより多くのカラムを、ポートレート方向ではより多くの行を使用し、コンテナの形状に自然に適応します。
ユースケース
コンテナのアスペクト比が最適なレイアウト方向を決定するパネル、モーダル、または埋め込みウィジェットにorientation コンテナクエリを使用してください。明示的な高さを持つcontainer-type: sizeが必要です。