HTML <source> media 屬性

定義和用法

media 屬性接受任何通常在 CSS 中定義的有效媒體查詢。

注意:此屬性可以接受多個值。

實例

一個包含兩個源文件和一個后備圖像的 <picture> 元素:

<picture>
  <source media="(min-width:650px)" srcset="flower-1.jpg">
  <source media="(min-width:465px)" srcset="flower-2.jpg">
  <img src="flower-3.jpg" alt="Flowers" style="width:auto;">
</picture>

親自試一試

語法

<source media="media_query">

可能的運算符

運算符 描述
and 規定 AND 運算符。
not 規定 NOT 運算符。
, 規定 OR 運算符。

設備

描述
all 默認。適合所有設備。
aural 語音合成器。
braille 盲文反饋裝置。
handheld 手持設備(小屏幕、有限的帶寬)。
projection 投影機。
print 打印預覽模式/打印頁面。
screen 計算機屏幕。
tty 電傳打字機以及使用等寬字符網格的類似媒介。
tv 電視類型設備(低分辨率、有限的分頁能力)。

描述
width

規定目標顯示區域的寬度。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (min-width:500px)"

height

規定目標顯示區域的高度。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (max-height:700px)"

device-width

規定目標顯示器/紙張的寬度。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (device-width:500px)"

device-height

規定目標顯示器/紙張的高度。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (device-height:500px)"

orientation

規定目標顯示器/紙張的方向。

可能的值:"portrait" 或 "landscape"

例子:media="all and (orientation: landscape)"

aspect-ratio

規定目標顯示區域的寬度/高度比。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (aspect-ratio:16/9)"

device-aspect-ratio

規定目標顯示器/紙張的 device-width/device-height 比率。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (aspect-ratio:16/9)"

color

規定目標顯示器的每種顏色的位數。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (color:3)"

color-index

規定目標顯示器能夠處理的顏色數。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (min-color-index:256)"

monochrome

規定在單色幀緩沖中的每像素比特。

可使用 "min-" 和 "max-" 前綴。

例子:media="screen and (monochrome:2)"

resolution

規定目標顯示器/紙張的像素密度 (dpi 或 dpcm)。

可使用 "min-" 和 "max-" 前綴。

例子:media="print and (resolution:300dpi)"

scan

規定 tv 顯示器的掃描方法。

可能的值是:"progressive" 和 "interlace"。

例子:media="tv and (scan:interlace)"

grid

規定輸出設備是網格還是位圖。

可能的值:"1" 代表網格,"0" 是其他。

例子:media="handheld and (grid:1)"

瀏覽器支持

表中的數字注明了首個完全支持該屬性的瀏覽器版本。

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
38.0 9.0 15.0 9.1 25.0