HTML
Images are inserted with img tags: <img src="" alt="">.
Note that images are not block elements.
The alt attribute is used to assistive technology, such as screen readers. It also works when images don’t load.
Other optional attributes are as follows:
title→ Titles won’t be read by screen readers; it is used for when we mouse over imagewidth,height→ If we only include awidthattribute the image will be re-sized according to its aspect ratio. We often want to provide both to avoid Cumulative layout shift.loading→ Defaults toeager, we can switch it tolazyso that images below the fold of the website will only load once we scroll to them
Figure
We can use the figure tag to enclose an img tag and declare it a figure. This allows us to add a figcaption tag to add a caption to the image. This will also help with assistive reading tech.
Note that the figcaption must be either the first or the last element inside the figure tags.
CSS
When using an image, we should still declare its width and height in HTML, even though CSS will override it. This is because a failure of CSS will still allow the browser to handle the image as a fallback.
To add dimensions to an image, add the following to the img class:
.example img {
width: 25%;
height: auto;
}This makes the width of the image 25% of its container, and the height will be auto-adjusted (responsive) as the viewport changes.
Because an image is an inline element we can use a reset applied to all images so that they behave more appropriately:
img { display: block; }Of course, this will cause an image to take entire space of an element horizontally - and it will therefore stack with other elements.