HTML - Images

Inserting Images

The <img> Tag

To add images to an HTML document, use the <img> tag. The <img> tag is a self-closing tag, meaning it does not need a closing tag. The basic syntax for the <img> tag is as follows:

Example: Basic <img> Syntax

<img src="image-url" alt="alternative-text">

The src attribute tells the URL or path to the image file. It is a required attribute for the <img> tag. The value can be an absolute URL (pointing to an external resource) or a relative path (pointing to a file within your website's directory structure).

The alt attribute provides alternative text for the image. It is important for accessibility, as it describes the image content for users who cannot see the image (e.g., visually impaired users using screen readers). It is also shown when the image fails to load.

In addition to src and alt, the <img> tag supports other attributes such as width and height. These attributes allow you to set the size of the image in pixels. However, it is generally recommended to use CSS to control the size and layout of images for better flexibility and responsiveness.

Example: Image Tag with Attributes

<img src="example.jpg" alt="Example Image" width="500" height="300">

Image File Formats

HTML supports various image file formats, each with its own features and uses. The most commonly used formats are:

Format Description
JPEG - Best for photographs and complex images with many colors.
- Provides good compression, resulting in smaller file sizes.
- Supports lossy compression, which means some image quality is lost during compression.
PNG - Ideal for images with transparency or illustrations with sharp edges.
- Supports lossless compression, keeping image quality.
- Offers better quality than JPEG for images with fewer colors or text.
GIF - Commonly used for simple animations and graphics with limited colors.
- Supports transparency, but only with a single transparent color.
- Limited to 256 colors, making it less suitable for complex images.
SVG - A vector image format that is resolution-independent.
- Ideal for logos, icons, and illustrations that need to scale without losing quality.
- Defined using XML-based markup, allowing for interactivity and animation.

When choosing an image format, consider factors such as image content, file size, transparency requirements, and browser support. JPEG and PNG are widely supported across browsers, while SVG may need fallbacks for older browsers.

Image Positioning

The <img> tag is used to insert images into an HTML document, but you can control the positioning and layout of images using CSS. CSS has several properties that let you position images within your web page.

One way to position images is by using the float property. The float property lets you place an image to the left or right of the content around it. When an image is floated, the text or elements next to it will wrap around it.

Example: Using the 'float' property

<img src="example.jpg" alt="Example Image" class="float-left">
<p>This is some text that will wrap around the floated image.</p>
.float-left {
  float: left;
  margin-right: 10px;
}

In this example, the image is floated to the left using float: left, and a right margin is added to create space between the image and the text next to it.

Another way to position images is by using the display property. By default, images are inline elements, meaning they flow within the text. However, you can change how images are displayed using values such as block, inline-block, or flex.

Example: Using the 'display' property

<img src="example.jpg" alt="Example Image" class="display-block">
.display-block {
  display: block;
  margin: 0 auto;
}

In this case, the image is displayed as a block-level element using display: block, and it is centered horizontally using margin: 0 auto.

The position property is another tool for image positioning. It lets you position images relative to their normal position (position: relative), relative to the nearest positioned ancestor (position: absolute), or fixed to the browser window (position: fixed).

Example: Using the 'position' property

<div class="container">
  <img src="example.jpg" alt="Example Image" class="position-absolute">
</div>
.container {
  position: relative;
  height: 400px;
}

.position-absolute {
  position: absolute;
  top: 20px;
  left: 20px;
}

In this example, the image is positioned absolutely 20 pixels from the top and left of its nearest positioned ancestor (the <div> with the class container).

By combining these CSS positioning techniques with other properties like margin, padding, and z-index, you can control the placement and layout of images within your web pages. Try different positioning methods to find the best approach for your design needs.

Responsive Images

HTML provides several techniques to create responsive images.

One way to serve responsive images is by using the srcset attribute on the <img> tag. The srcset attribute allows you to specify multiple image sources along with their respective widths or pixel densities. The browser can then choose the most appropriate image based on the device's screen size and resolution.

Example: Using the srcset attribute

<img src="image-small.jpg"
     srcset="image-small.jpg 400w,
             image-medium.jpg 800w,
             image-large.jpg 1200w"
     alt="Responsive Image">

The srcset attribute provides three different image sources with their corresponding widths (400w, 800w, and 1200w). The browser will select the image that best matches the device's screen size and resolution.

Another technique for responsive images is using the <picture> element. The <picture> element acts as a container for multiple <source> elements, each specifying different image sources and media queries. This allows you to define different images for different screen sizes or device characteristics.

Example: Using the picture element

<picture>
  <source media="(min-width: 1200px)" srcset="image-large.jpg">
  <source media="(min-width: 800px)" srcset="image-medium.jpg">
  <img src="image-small.jpg" alt="Responsive Image">
</picture>

The <picture> element contains two <source> elements with media queries. The first <source> element specifies an image for screens with a minimum width of 1200px, while the second <source> element targets screens with a minimum width of 800px. The <img> element inside the <picture> element serves as a fallback for browsers that do not support the <picture> element.

Art Direction is another concept related to responsive images. Art Direction involves serving different image crops or compositions based on the device's screen size or aspect ratio. This ensures that the most important parts of the image are visible on different devices.

Example: Using Art Direction with the picture element

<picture>
  <source media="(min-width: 1200px)" srcset="image-large.jpg">
  <source media="(min-width: 800px)" srcset="image-medium-cropped.jpg">
  <img src="image-small-cropped.jpg" alt="Responsive Image">
</picture>

The <source> elements inside the <picture> element specify different image crops for different screen sizes. The image "image-medium-cropped.jpg" and "image-small-cropped.jpg" are cropped versions of the original image, optimized for medium and small screens, respectively.

By using responsive image techniques like srcset, <picture>, and Art Direction, you can provide an optimal viewing experience for users across various devices. These techniques help you serve images that are appropriate for different screen sizes, resolutions, and aspect ratios, resulting in faster page loads and improved user engagement.

Accessibility

Accessibility is an important part of web design, making sure that your content can be used by everyone, including those with disabilities. When it comes to images, there are several things to keep in mind to improve accessibility.

Providing alternative text for images is important. Alternative text, or "alt text," is a short description of an image that is shown when the image cannot be loaded or is read aloud by screen readers for visually impaired users. The alt attribute of the <img> tag is used to provide this alternative text.

Example: Alternative Text for Images

<img src="example.jpg" alt="A sunset over the ocean">

When writing alternative text, try to describe the content and purpose of the image in a short way. For decorative images that do not add meaningful content, you can leave the alt attribute empty (alt="").

For complex images, such as charts, graphs, or diagrams, providing a short alternative text may not be enough. In these cases, you can use the longdesc attribute to provide a link to a detailed description of the image. Or, you can include the description in the main text near the image.

Example: Long Description for Complex Images

<img src="chart.jpg" alt="Sales chart" longdesc="chart-description.html">

In the above example, the longdesc attribute points to an HTML file (chart-description.html) that contains a detailed description of the chart.

Another accessibility best practice is to avoid using images for text. While it may be tempting to use images to show stylized text or headings, this can be a problem for screen readers and users with visual impairments. Instead, use actual text and style it with CSS. This makes sure that the text is accessible, selectable, and can be resized by users if needed.

Example: Stylized Text with CSS

<h1 class="stylized-heading">Welcome to Our Website</h1>
.stylized-heading {
  font-family: "Decorative Font", cursive;
  font-size: 36px;
  color: #ff0000;
}

By using CSS to style the text, you keep accessibility while still getting the desired visual effect.

In summary, to improve image accessibility:

Guidelines Description
Provide alternative text Use the alt attribute for all informative images.
Use longdesc or nearby text For complex images that need detailed descriptions.
Avoid using images for text Use actual text and style it with CSS instead.

By following these accessibility guidelines, you make sure that your images can be understood by all users, creating a more inclusive web experience.

Image Maps

Image maps let you create clickable areas on an image, turning different parts of the image into interactive links. This technique is useful when you want to provide multiple links within a single image or create a navigation system based on an image.

To create an image map, you need to use the <map> and <area> tags together with an <img> tag. The <map> tag defines the image map and gives it a name, while the <area> tags define the clickable areas within the image.

Example: Image Map HTML Code

<img src="image.jpg" alt="Image Map" usemap="#imagemap">

<map name="imagemap">
  <area shape="rect" coords="0,0,100,100" href="link1.html" alt="Link 1">
  <area shape="circle" coords="200,200,50" href="link2.html" alt="Link 2">
  <area shape="poly" coords="300,100,350,200,250,200" href="link3.html" alt="Link 3">
</map>
Step Description
1 The <img> tag shows the image and uses the usemap attribute to reference the image map defined by the <map> tag.
2 The <map> tag is given a name using the name attribute, which matches the value of the usemap attribute in the <img> tag.
3 Inside the <map> tag, multiple <area> tags define the clickable areas within the image.
4 Each <area> tag has a shape attribute that specifies the shape of the clickable area. The available shapes are:
- rect: A rectangular area defined by the coordinates of its top-left and bottom-right corners.
- circle: A circular area defined by the coordinates of its center and radius.
- poly: A polygonal area defined by a series of coordinate pairs representing the vertices of the polygon.
5 The coords attribute of the <area> tag specifies the coordinates of the clickable area based on the chosen shape. The coordinates are measured in pixels from the top-left corner of the image.
6 The href attribute of the <area> tag specifies the URL or link that the user will be directed to when clicking on that specific area.
7 The alt attribute provides alternative text for each clickable area, which is important for accessibility.

When defining the coordinates for the clickable areas, you need to know the exact pixel locations of the desired regions within the image. You can use image editing software or online tools to find these coordinates.

Image maps are not as commonly used nowadays due to the rise of responsive web design and the difficulty in creating and maintaining accurate coordinates for different image sizes. However, in certain cases, such as creating interactive infographics or providing links within a specific image, image maps can still be a useful technique.

When using image maps, make sure to provide clear and descriptive alternative text for each clickable area to guarantee accessibility for users who rely on assistive technologies.

Background Images

In addition to inserting images into HTML documents using the <img> tag, you can also set images as backgrounds for elements using CSS. Background images can enhance the visual appeal of your web pages and create interesting effects.

To set a background image for an element, use the background-image property in CSS. The value of this property is a URL that points to the image file you want to use as the background.

Example: Setting a background image

.element {
  background-image: url("background.jpg");
}

By default, background images repeat both horizontally and vertically to cover the entire element. However, you can control the repetition behavior using the background-repeat property. The available values are:

Value Description
repeat The default value. The image repeats both horizontally and vertically.
repeat-x The image repeats only horizontally.
repeat-y The image repeats only vertically.
no-repeat The image does not repeat and appears only once.

Example: Controlling background repetition

.element {
  background-image: url("background.jpg");
  background-repeat: no-repeat;
}

You can also control the positioning of the background image using the background-position property. This property takes two values: the horizontal position and the vertical position. The values can be keywords (left, center, right for horizontal; top, center, bottom for vertical) or specific lengths (e.g., pixels or percentages).

Example: Positioning a background image

.element {
  background-image: url("background.jpg");
  background-repeat: no-repeat;
  background-position: center center;
}

Background images can be used to create interesting visual effects, such as parallax scrolling. Parallax scrolling is a technique where the background image moves at a different speed than the content on the page, creating a sense of depth.

Example: Creating a parallax effect

.parallax {
  background-image: url("parallax-background.jpg");
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 500px;
}

To create a parallax effect:

  1. Set the background image using background-image.
  2. Use background-attachment: fixed to fix the background image in place while the page content scrolls over it.
  3. Position the background image as desired using background-position.
  4. Set background-repeat: no-repeat to prevent the image from repeating.
  5. Use background-size: cover to make sure the image covers the entire element, even if it needs to be resized.
  6. Set a sufficient height for the element to create the parallax scrolling effect.

When using background images, keep the following best practices in mind:

  • Optimize your images for the web to keep file sizes small and page load times fast.
  • Use appropriate image formats (e.g., JPEG for photographs, PNG for images with transparency).
  • Consider the readability of the content when choosing background images. Make sure there is enough contrast between the text and the background.
  • Be mindful of accessibility. Provide alternative text or descriptions for background images if they convey important information.