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 像素 以像素或百分比设置图像的宽度。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

HTML img 标签示例

下面的示例将说明 img 标签的使用方法。在何处、何时以及如何使用 img 标签,以及如何使用 CSS 操作 img 元素。

使用 img 标签插入图片

让我们考虑以下示例,我们将使用<img>标签将图像上传到 HTML 页面。它将生成一个输出,其中包含上传到网页的图像

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

使用 CSS 对齐图像元素

考虑另一种情况,我们将使用 CSS 以及<img>标签对齐图像。

Open Compiler
<!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>标签内,使图像成为链接。

Open Compiler
<!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.com/index.htm"> <img src="https://tutorialspoint.com/images/logo.png?v2" height="55" width="200"> </a> </body> </html>

图像加载失败的替代方案

在以下示例中,我们将使用 alt 属性,并使用 CSS 样式化<img>标签。

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

支持的浏览器

标签 Chrome Edge Firefox Safari Opera
img
html_tags_reference.htm
广告