HTML - <img> 標籤



HTML <img> 標籤用於將影像嵌入到 HTML 文件中。它是一個內聯且為空的元素,因此它不會在新行開始,也不需要結束標籤。

一個<img>元素必須有兩個屬性 src,它從該源獲取影像,以及 alt,它指定圖片的替代文字。瀏覽器會插入<img>標籤中提供的源提供的 HTML 影像,而不是直接將圖片插入文件中。

語法

<img src="..."  alt="...">

屬性

HTML img 標籤支援 HTML 的全域性事件屬性。以及一些特定的屬性,如下所示。

屬性 描述
alt 文字 指定替代文字。
crossorigin anonymous
use-credentials
它允許來自允許跨源訪問的第三方站點的影像與畫布一起重複使用。
height 畫素 指定影像的高度。
ismap ismap 將影像定義為伺服器端影像地圖。
loading eager
lazy
指定影像何時載入。
longdesc URL 指定附加影像的長描述。
referrerpolicy no-referrer
no-referrer-when-downgrade
origin
origin-when-cross-origin
unsafe-url
指定哪個推薦人資訊。
sizes sizes 為不同的情況指定影像大小。
src URL 指定將顯示的影像 URL。
srcset URL 列表 指定在不同情況下使用的影像檔案列表。
usemap #mapname 將影像定義為客戶端影像地圖,並與<map>和<area>標籤一起使用。
width 畫素 以畫素或百分比設定影像的寬度。

HTML img 標籤示例

下面的示例將說明 img 標籤的使用方法。在何處、何時以及如何使用 img 標籤,以及如何使用 CSS 操作 img 元素。

使用 img 標籤插入圖片

讓我們考慮以下示例,我們將使用<img>標籤將影像上傳到 HTML 頁面。它將生成一個輸出,其中包含上傳到網頁的影像

<!DOCTYPE html>
<html>
<head>
   <title>HTML Tag</title>
</head>
<body>
   <img src="https://tutorialspoint.tw/cg/images/logo.png" 
        alt="HTML Tutorial" height="150" width="390" />
</body>
</html>

使用 CSS 對齊影像元素

考慮另一種情況,我們將使用 CSS 以及<img>標籤對齊影像。

<!DOCTYPE html>
<html>
<body>
   <h2>Image vertical-align: middle</h2>
   <p>
       Pawan Kalyan 
       <img src=
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRB3tcOH6bebY1QFANMOUDhGU0nI3fTaKqP2qEKxBxpRKKBL5Y-51iu&usqp=CAE&s" 
            width="42" height="42" style="vertical-align:middle">
       is an Indian actor, politician, filmmaker, and 
       philanthropist. He primarily works in Telugu cinema.
       He is the recipient of a Filmfare Award, a SIIMA Award,
       a CineMAA Award and a Santosham Film Award.
   </p>
   <h2>Image vertical-align: top</h2>
   <p>
       Mahendra Singh Dhoni 
       <img src=
"https://upload.wikimedia.org/wikipedia/commons/7/70/Mahendra_Singh_Dhoni_January_2016_%28cropped%29.jpg"
            width="42" height="42" style="vertical-align:top">
       is an former Indian cricketer. He was captain of 
       the Indian national team in limited-overs formats 
       from 2007 to 2017 and in Test cricket from 2008 to 2014. 
   </p>
</body>
</html>

可點選的影像

以下是一個示例,我們將把<image>標籤放在<a>標籤內,使影像成為連結。

<!DOCTYPE html>
<html>

<head>
    <title>Image tag</title>
</head>

<body>
    <h2>TUTORIALSPOINT</h2>
    <p>Click on the image to direct to webpage.</p> 
    <a href="https://tutorialspoint.tw/index.htm">
        <img src="https://tutorialspoint.tw/images/logo.png?v2" 
             height="55" width="200"> 
    </a> 
</body>

</html>

影像載入失敗的替代方案

在以下示例中,我們將使用 alt 屬性,並使用 CSS 樣式化<img>標籤。

<!DOCTYPE html>
<html>
<body>
   <div>
      <img src="https://tutorialspoint.tw/cg/images/ogo.png"
           alt="Tutorialspoint_Logo" width="100" height="106">
   </div>
</body>
</html>

支援的瀏覽器

標籤 Chrome Edge Firefox Safari Opera
img
html_tags_reference.htm
廣告

© . All rights reserved.