回應式圖片通常是使用 srcset
屬性實作。srcset
屬性是以逗號分隔的圖片檔案名稱清單,以及其寬度或密度描述元。為避免版面配置位移,請在使用 srcset
的 <img>
和 <source>
標記上設定 width
和 height
屬性。
使用密度描述元的回應式圖片:
src
和srcset
中列出的所有圖片的長寬比都應相同。- 設定
width
和height
屬性以符合1x
圖片的尺寸。 src
屬性應參照1x
圖片。
若為使用寬度描述元的回應式圖片:
- 「
src
」和「srcset
」中列出的所有圖片的長寬比都必須相同。 - 設定
width
和height
屬性以符合備用圖片的尺寸。 - 視需要調整圖片樣式:如果沒有任何 CSS 樣式,在使用寬度描述元的回應式圖片上設定
width
和height
,會導致圖片始終以相同大小顯示,即使srcset
中列出的圖片尺寸不同亦然。這可能不是你想要的行為。 在圖片樣式中加入width: 100%; height: auto;
或width: 100vw; height: auto;
,即可獲得所需的視覺外觀。
如為 <Picture> 標記:
- 為所有
<source>
標記設定width
和height
屬性:width
和height
的適用值取決於<source>
標記使用srcset
的方式。(如需瞭解與srcset
合作的相關資訊,請參閱上方說明)。 - 調整圖片樣式:如需調整圖片樣式,請注意在
<source>
標記中新增樣式並不會有任何作用,而<source>
標記是空白元素。您必須改為設定對應的<img>
標記樣式。 - 在
<img>
標記上設定width
和height
屬性:這些值應與備用圖片的內建函式大小相符。
HTML
<!-- Using density descriptors -->
<img width="480" height="330"
srcset="cat-1x.jpg, cat-2x.jpg 2x, cat-3x.jpg 3x"
src="cat-1x.jpg"
alt="Photo of a cat on a green background">
<!-- Using width descriptors -->
<img width="256" height="128"
srcset="dog-256w.jpg 256w, dog-512w.jpg 512w, dog-1028w.jpg 1028w"
src="dog-256w.jpg"
alt="Photo of a dog on a orange background">
<!-- Picture tag -->
<picture>
<source media="(max-width: 720px)" width="600" height="300" srcset="newyork-rectangle.jpg" />
<source media="(min-width: 721px)" width="600" height="600" srcset="newyork-square-1x.jpg, newyork-square-2x.jpg 2x, newyork-square-3x.jpg 3x" />
<img src="newyork-rectangle.jpg" width="600" height="300" alt="Photo of the Empire State Building">
</picture>