Imagine opening this page on a slow phone connection. The media should still be worth the wait and have a sensible fallback.
What You Need to Know
Put an image in HTML when it contributes meaning to the content. Use a CSS background when it is only decoration. A background image does not provide useful alt text on its own.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<article>
<h2>Robot project</h2>
<img src="images/robot.jpg" alt="Small two-wheeled robot on a classroom table" width="600" height="400">
<p>Our team built this robot in science class.</p>
</article>
<style>
article { background-color: #eef5ff; padding: 1rem; }
</style>
Let’s Read the Code
- <h2>: A heading divides the page into understandable parts.
- <img>: The img displays a picture; its alt is the text alternative.
- src: Src identifies a resource path for images, frames, or media.
- width: Width gives a preferred or intrinsic media width, depending on the element.
What the example shows: The robot photo belongs in HTML because it carries information; the pale background color belongs in CSS because it is decorative.
What Happens in the Browser?
The paths shown here refer to files in your own example project. Put real images and recordings in those locations before expecting them to load.
What if the resource is missing? Test the page with the media path temporarily broken. The surrounding text should still explain the important idea, and controls should remain understandable. This is especially important for slow connections and accessibility.
Your Turn
Decide whether a patterned backdrop should be an img or a CSS background.
Common Beginner Mistakes
- Leaving out real media files or understandable text alternatives.
- A meaningful image should not be hidden solely inside CSS where it lacks a normal alt text alternative.
Key Takeaways
- Put an image in HTML when it contributes meaning to the content.
- <h2>: A heading divides the page into understandable parts.
- If the resource cannot load, users still need enough text to understand what was meant to be there.