Skip to content

04‐ Working with Images

Sanjay Viswanathan edited this page May 28, 2025 · 1 revision

Inserting an Image

To insert an image in HTML, you use the tag with the src attribute, which specifies the URL of the image file. Here's an example of inserting an image into a web page:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Example</title>
</head>
<body>
  <h1>My Pet</h1>
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Dog_Breeds.jpg/800px-Dog_Breeds.jpg" alt="A cute dog" />
</body>
</html>

image

Image Attributes

The tag supports several attributes that control the appearance and behavior of images on web pages. Here are some commonly used attributes:

src: Specifies the URL of the image file. alt: Provides alternative text for the image (required for accessibility). width: Sets the width of the image in pixels or as a percentage of the containing element. height: Sets the height of the image in pixels or as a percentage of the containing element. title: Adds a title or tooltip to the image that is displayed when the user hovers over it. style: Applies CSS styles to the image, such as colors, borders, margins, and padding. class: Assigns a class name to the image for styling and scripting purposes. id: Specifies a unique identifier for the image that can be used for scripting or styling.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Example</title>
</head>
<body>
  <h1>My Pet</h1>
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Dog_Breeds.jpg/800px-Dog_Breeds.jpg" alt="A cute dog" />
</body>
</html>

image

The alt Attribute The alt attribute provides alternative text for the image, which is displayed if the image cannot be loaded or accessed by the user. It is also used by screen readers to describe the content of the image to visually impaired users.

Here's an example of using the alt attribute with an image:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Example</title>
</head>
<body>
  <h1>My Pet</h1>
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Dog_Breeds.jpg/800px-Dog_Breeds.jpg" alt="A cute dog" />
</body>
</html>

Learn Docs

Clone this wiki locally