orientation

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

orientation CSS 媒體特性 可用於測試 視口 的方向(或 分頁媒體 的頁框)。

注意:此特性不對應於裝置方向。在許多裝置的縱向模式下開啟軟鍵盤將導致視口變得比其高,從而導致瀏覽器使用橫向樣式而不是縱向樣式。

語法

orientation 特性被指定為從下面的列表中選擇的關鍵字值。

關鍵字值

portrait(縱向)

視口處於縱向模式,即高度大於或等於寬度。

landscape(橫向)

視口處於橫向模式,即寬度大於高度。

示例

縱向模式

在此示例中,HTML 中有三個盒子,並使用 orientation 媒體特性在行佈局(橫向)和列布局(縱向)之間切換。

示例輸出嵌入在高度大於寬度的 <iframe> 中,因此盒子採用列布局。

HTML

html
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>

CSS

css
body {
  display: flex;
}

div {
  background: yellow;
  width: 200px;
  height: 200px;
  margin: 0.5rem;
  padding: 0.5rem;
}

@media (orientation: landscape) {
  body {
    flex-direction: row;
  }
}

@media (orientation: portrait) {
  body {
    flex-direction: column;
  }
}

結果

橫向模式

此示例的程式碼與上一個示例完全相同:HTML 中有三個盒子,並使用 orientation 媒體特性在行佈局(橫向)和列布局(縱向)之間切換。

然而,在此示例中,示例輸出嵌入在高度小於寬度的 <iframe> 中,因此盒子採用行佈局。

HTML

html
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>

CSS

css
body {
  display: flex;
}

div {
  background: yellow;
  width: 200px;
  height: 200px;
  margin: 0.5rem;
  padding: 0.5rem;
}

@media (orientation: landscape) {
  body {
    flex-direction: row;
  }
}

@media (orientation: portrait) {
  body {
    flex-direction: column;
  }
}

規範

規範
媒體查詢第 4 級
# orientation

瀏覽器相容性