Media
Images
Images are displayed with the IMG
tag. The IMG
tag does not have a closing tag, and thus cannot enclose text or other elements.
Set the src
attribute to indicate the location of the image. Because this is just a URL, it can be located anywhere. In the below snippet, we presume that there is a file "photo.jpg" in the same location as the HTML.
<img src="photo.jpg">
Try to keep your media filenames simple and without punctuation so that it's easier to know what to set for the src
attribute.
For accessibility, you should set the alt
attribute to describe the image. This is so screen readers for the visually impaired can present the contents for these users.
<img alt="Photograph of the car" src="photo.jpg">
To align images in the flow of the document, use the vertical-align
CSS property, which can be set to one of: baseline, top, bottom, middle, text-top, text-bottom, sub, super, and length.
<img alt="Photograph of the car" src="photo.jpg">
img {
vertical-align: middle;
}
You can use other CSS sizing properties to set the size of the image.
Reference
- IMG element (MDN)
- vertical-align (CSS Tricks)
Tip
- Use a placeholder image while you're working on layouts
Sound
You can playback sound using the AUDIO
element. If you want to synthesise sound or work with sound effects, read up on the Web Audio API.
Here is an example:
<audio src="myMedia.mp3">
<p>Audio is not supported</p>
</audio>
Note that the content inside the tag will not appear if the browser supports audio playback.
You can also add attributes to turn on playback control, automatically play the sound and to loop:
<audio src="myMedia.mp3" controls autoplay loop>
<p>Audio is not supported</p>
</audio>
Reference
- AUDIO element (W3C)
- AUDIO element (MDN)
Video
Video playback uses the VIDEO
element, which works in quite the same way as the AUDIO
element:
<video src="myVideo.ogv">
<p>Video is not supported</p>
</video>
The child elements of the tag are only shown if the user's browser does not support VIDEO
.
It has several useful attribute flags: autoplay, preload, controls, loop and muted.
<video autoplay preload loop muted src="myVideo.ogv">
<p>Video is not supported</p>
</video>
Reference
- VIDEO element (W3C)
- VIDEO element (MDN)
SVG
Scalable Vector Graphics (SVG) are great for diagrams, icons and animation.
Read more
There are a lot more media features to HTML which we don't describe. The CANVAS element is particularly powerful. It allows you to manipulate pixels and draw using various primitive shapes. Another important element is SVG for showing complicated vector shapes in HTML.
More
- Using audio and video (MDN)