HTML Element: img | Envato Tuts+

HTML Element: img | Envato Tuts+

[ad_1]

The HTML <img> element is one of the first elements developers learn, and it’s used to embed images in web documents. It is an empty element and contains attributes only.

The primary purpose of the <img> element is to enhance the visual appeal and interactivity of web pages by displaying images. It was created to address the growing need for presenting graphical content on the World Wide Web, which has evolved into a multimedia-rich environment.

Syntax

The basic syntax of the <img> element is as follows:

1
<img src="url/to/image.jpg" alt="alternative text">

Example

Here is an example of how to use the <img> element:

1
<img src="farm.jpg" alt="A beautiful farm landscape">

In the embedded demo here, you’ll see the first image (which is 500×500px by default) has burst beyond the boundaries of its containing <figure> element.

The second image, even though it has width and height attributes set on the <img> element, is fluid and neatly contained within its fixed parent element. The CSS needed for this is:

1
img {
2
    width: 100%; /* this makes the image width 100% of its containing element */   
3
    height: auto; /* some browsers need this to make sure the height stays in proportion to the width */
4
}
5
    

Lastly, the final image hasn’t been found by the browser, so a broken image icon is shown, along with the ALT (alternative) text.

Attributes

The <img> element supports global attributes and includes several additional attributes:

  • src: Specifies the image file’s web address.
  • alt: Provides alternative text for accessibility.
  • width: Sets image width.
  • height: Sets image height.
  • title: Adds a tooltip with extra information.
  • srcset: Offers responsive image options.
  • sizes: Helps choose the right image for the viewport.
  • crossorigin: Manages cross-origin image requests.
  • usemap: Links to server-side image maps.
  • ismap: Indicates server-side image map use.
  • referrerpolicy: Controls referrer information sent.
  • decoding: Optimizes image decoding.
  • loading: Controls image loading behavior.
  • fetchpriority: Provides hints for resource loading priority.

Content

The <img> element is empty and does not accept content or have closing tags.

Did You Know?

  • The alt attribute is important for accessibility, as it describes the image for those who cannot see it.
  • You can actually style an image’s alt tag using CSS.
  • If the src attribute is not present, the <img> tag will be ignored.

Learn More

[ad_2]

We will be happy to hear your thoughts

      Leave a reply

      WebForgers
      Logo
      Enable registration in settings - general