By the end of this lesson, you will understand how to add images to web pages using the <img> tag. You will be able to write accessible image markup with proper alt text, understand different image file formats and when to use them, and control image size and positioning using both HTML attributes and CSS. You will also learn how to make images responsive so they work well on all screen sizes.
You should be comfortable with basic HTML document structure from Lesson 01, and have some familiarity with CSS basics from Lesson 03. Understanding file paths and folder structures will also be helpful.
Images are a fundamental part of the web experience. They help communicate ideas, break up text, create visual interest, and make content more engaging and memorable. Whether you're building a portfolio to showcase your work, creating a blog with photos, or developing a business website with product images, understanding how to work with images effectively is essential.
On the web, images fulfill several important roles:
Unlike printed images, web images must work across different devices, screen sizes, and connection speeds. An image that looks perfect on your desktop might be too large for a mobile phone, or might take too long to download on a slow connection. Learning to work with images on the web means understanding not just how to display them, but how to make them accessible, performant, and responsive.
This lesson will teach you the foundational skills you need to add images to your web pages thoughtfully and effectively.
Images are added to HTML documents using the <img> tag. Unlike most HTML elements you've learned so far, the image tag is self-closing, meaning it doesn't have a closing tag. This makes sense because images don't contain other HTML content - they simply display a picture.
The simplest form of an image tag looks like this:
<img src="photo.jpg" alt="A description of the photo">
Every image tag needs two essential attributes to function properly:
src AttributeThe src attribute (short for "source") tells the browser where to find the image file. This can be:
"images/photo.jpg")"/images/photo.jpg")"https://example.com/photo.jpg")Without a src attribute, the browser doesn't know what image to display, and you'll typically see a broken image icon.
alt AttributeThe alt attribute (short for "alternative text") provides a text description of the image. This text serves multiple crucial purposes:
Important: While some browsers may technically allow you to omit the alt attribute, doing so creates accessibility barriers and is considered bad practice. Every image should have an alt attribute, even if it's empty (which we'll discuss later).
Beyond src and alt, images can have additional attributes:
width and height - Specify the display dimensions in pixelstitle - Provides additional information (appears as a tooltip on hover)loading - Controls when the image loads ("lazy" defers loading until needed)<img src="landscape.jpg"
alt="Mountain landscape at sunset"
width="800"
height="600"
loading="lazy">
One of the most common issues when working with images is getting the file path correct. The file path tells the browser where to find your image file, and understanding how paths work is essential for displaying images successfully.
A relative path describes the location of a file relative to the current HTML file. This is the most common way to reference images on your own website.
Common relative path patterns:
src="photo.jpg" - Image is in the same folder as the HTML filesrc="images/photo.jpg" - Image is in an images subfoldersrc="../photo.jpg" - Image is in the parent folder (up one level)src="../../images/photo.jpg" - Go up two levels, then into images folderImagine you have this folder structure:
my-website/
├── index.html
├── pages/
│ └── about.html
└── images/
└── logo.png
To display logo.png in index.html, you would use:
<img src="images/logo.png" alt="Company logo">
But to display the same image in about.html, you need to go up one folder level first:
<img src="../images/logo.png" alt="Company logo">
The ../ means "go up one folder level." From pages/about.html, you go up to my-website/, then down into images/.
An absolute path starts from the root of your website, beginning with a forward slash /:
<img src="/images/logo.png" alt="Company logo">
This path works the same way from any page on your site, because it always starts from the root. However, absolute paths won't work when viewing files locally on your computer - they only work on a web server.
You can also link to images hosted on other websites using a full URL:
<img src="https://example.com/images/photo.jpg" alt="Example photo">
Note: While this works technically, it's generally better to host important images on your own server so you control their availability and performance.
If your image doesn't appear, the most likely cause is an incorrect path. Check:
../ to go up folders?The alt attribute is one of the most important aspects of accessible web design, yet it's often overlooked or poorly implemented. Good alt text makes your website usable for everyone, regardless of how they access your content.
Effective alt text should be concise but descriptive, conveying the essential information or purpose of the image. Think about what information the image communicates, not just what it looks like.
When an image conveys information, describe that information:
<!-- Not ideal -->
<img src="chart.png" alt="A chart">
<!-- Better -->
<img src="chart.png" alt="Bar chart showing sales increased 40% in Q3">
If an image is purely decorative and doesn't add information, use an empty alt attribute:
<img src="decorative-border.png" alt="">
Note that this is alt="" (empty quotes), not omitting the alt attribute entirely. The empty alt tells screen readers to skip the image, which is appropriate for decoration.
If an image is part of a link or button, describe the function or destination, not the image:
<!-- Not ideal -->
<img src="home-icon.png" alt="House icon">
<!-- Better -->
<img src="home-icon.png" alt="Return to home page">
Follow these guidelines when writing alt text:
For complex images like detailed charts or infographics, you might need to provide additional description beyond the alt text. You can:
<figure> element with <figcaption> to provide a longer caption<figure>
<img src="complex-diagram.png"
alt="Flowchart of website deployment process">
<figcaption>
This diagram shows the five stages of deployment:
development, testing, staging, review, and production.
</figcaption>
</figure>
Different image formats are optimized for different purposes. Choosing the right format helps ensure your images look good while loading quickly.
Best for: Photographs and images with many colors
Use JPEG for photos, complex images, and anywhere file size is important. JPEG compression can be adjusted to balance quality versus file size.
Best for: Graphics, logos, images needing transparency
Use PNG for logos, icons, screenshots, and any image where you need transparent backgrounds or very sharp edges.
Best for: Simple animations, very simple graphics
GIFs are most commonly used for simple animations. For static images, PNG is usually a better choice.
Best for: Icons, logos, illustrations
SVG files are vector graphics rather than pixel-based images. They remain crisp at any size, making them perfect for logos and icons that need to work on both small phone screens and large desktop displays.
Best for: Modern websites prioritizing performance
WebP is a newer format that often provides better compression than JPEG or PNG. It's increasingly popular for modern web development.
A simple decision guide:
You can control image size using either HTML attributes or CSS properties. Understanding when to use each approach helps you create flexible, maintainable websites.
You can specify image dimensions directly in the HTML using width and height attributes:
<img src="photo.jpg"
alt="Beach sunset"
width="600"
height="400">
These values are in pixels and tell the browser the exact dimensions to display the image.
Specifying dimensions in HTML helps with page performance:
Important: If you only specify width or height (not both), browsers will automatically calculate the other dimension to maintain the image's aspect ratio:
<!-- Image will scale height automatically -->
<img src="photo.jpg" alt="Beach sunset" width="600">
However, if you specify both width and height with values that don't match the image's natural aspect ratio, the image will be distorted. Generally, it's safer to specify only one dimension or use CSS for more control.
CSS provides much more flexibility for controlling image size:
img {
width: 100%;
height: auto;
}
This CSS makes the image fill its container's width while automatically adjusting height to maintain aspect ratio.
img {
width: 300px;
height: 200px;
}
img {
width: 100%;
height: auto;
}
img {
max-width: 100%;
height: auto;
}
This is a very common pattern for responsive images. The image will shrink to fit smaller containers, but won't stretch larger than its original size (which would make it blurry).
img {
width: 300px;
height: 300px;
object-fit: cover; /* or contain */
}
The object-fit property controls how an image fills its container when you specify both dimensions:
cover - Image covers the entire container, may be croppedcontain - Entire image is visible, may have empty space in containerfill - Image stretches to fill container (may distort)By default, images are inline elements, which means they flow with text and other inline content. However, you often want more control over where images appear and how they interact with surrounding content.
Without any styling, an image sits on the same line as text:
<p>This is some text <img src="icon.png" alt="icon"> with an image inside.</p>
This works well for small icons within text, but larger images usually need different positioning.
To give an image its own line and enable centering, make it a block element:
img {
display: block;
}
Now the image appears on its own line, separate from surrounding text.
Once an image is a block element, you can center it using auto margins:
img {
display: block;
margin-left: auto;
margin-right: auto;
}
Or using the shorthand:
img {
display: block;
margin: 0 auto; /* 0 top/bottom, auto left/right */
}
To make text wrap around an image (like in a magazine), use the float property:
img {
float: left;
margin-right: 1rem;
margin-bottom: 1rem;
}
This positions the image on the left side with text flowing around it. The margins create space between the image and the text. Use float: right to position the image on the right side instead.
Note: Floated elements can cause layout issues if not cleared properly. You may need to apply clear: both to elements that should appear below the floated image.
Modern CSS layout with Flexbox provides more control and fewer quirks than floats:
<div class="content-with-image">
<img src="photo.jpg" alt="Example photo">
<div class="text">
<p>Text content goes here...</p>
</div>
</div>
.content-with-image {
display: flex;
gap: 1rem;
align-items: flex-start;
}
.content-with-image img {
width: 200px;
height: auto;
}
This creates a flexible layout where the image and text sit side by side, with a gap between them.
For inline images (like icons), the vertical-align property controls alignment with the surrounding text:
img.icon {
vertical-align: middle; /* or top, bottom, text-top, etc. */
}
Responsive images adapt to different screen sizes and devices, ensuring they look good and load efficiently everywhere. This is crucial in modern web development, where users access websites on phones, tablets, laptops, and large desktop screens.
The most basic approach to responsive images uses CSS:
img {
max-width: 100%;
height: auto;
}
This ensures images never overflow their container. The image will shrink to fit on small screens but won't stretch larger than its original size (which would make it blurry). The height: auto maintains the aspect ratio.
For a more complete responsive image solution:
img {
max-width: 100%;
height: auto;
display: block;
}
The display: block prevents small gaps that can appear below inline images.
Often you want images to fill a specific percentage of their container:
.image-container {
width: 100%;
max-width: 800px; /* Don't get too large */
margin: 0 auto; /* Center the container */
}
.image-container img {
width: 100%;
height: auto;
}
This pattern creates a container that centers on the page and never exceeds 800px wide, with the image filling that container.
Sometimes you want to serve different images to different devices - perhaps a smaller, cropped version for mobile phones. HTML provides the <picture> element for this:
<picture>
<source media="(max-width: 600px)" srcset="small-image.jpg">
<source media="(max-width: 1200px)" srcset="medium-image.jpg">
<img src="large-image.jpg" alt="Description of image">
</picture>
The browser will choose the appropriate image based on screen size. The final <img> tag serves as the fallback for larger screens and older browsers.
Responsive images aren't just about appearance - they're also about performance. A mobile phone doesn't need a 4000-pixel-wide image. Using appropriately sized images for each device saves bandwidth and improves loading speed.
This example demonstrates how to create a simple responsive image gallery that showcases multiple images in a grid layout. We'll combine several concepts from this lesson: proper image markup, alt text, responsive sizing, and CSS layout.
First, create the HTML markup for the gallery. We'll use a <div> container for the gallery and individual containers for each image:
<div class="gallery">
<figure class="gallery-item">
<img src="images/photo1.jpg"
alt="Mountain landscape with snow-capped peaks">
<figcaption>Rocky Mountains</figcaption>
</figure>
<figure class="gallery-item">
<img src="images/photo2.jpg"
alt="Ocean waves at sunset with orange sky">
<figcaption>Pacific Coast Sunset</figcaption>
</figure>
<figure class="gallery-item">
<img src="images/photo3.jpg"
alt="Dense forest with sunlight filtering through trees">
<figcaption>Forest Canopy</figcaption>
</figure>
<figure class="gallery-item">
<img src="images/photo4.jpg"
alt="Desert landscape with cacti and red rock formations">
<figcaption>Desert Vista</figcaption>
</figure>
</div>
Note: We're using the semantic <figure> element to wrap each image and its caption. This provides meaningful structure and groups related content together.
Now add CSS to create a responsive grid that adjusts to different screen sizes:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
}
What this does:
display: grid - Creates a grid layoutgrid-template-columns - Automatically fits as many columns as possible, each at least 250px widegap - Adds space between grid itemsmax-width and margin: 0 auto - Centers the gallery and prevents it from getting too wideAdd styling to the individual gallery items:
.gallery-item {
margin: 0;
background-color: #f8f9fa;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.gallery-item:hover {
transform: translateY(-5px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.gallery-item img {
width: 100%;
height: 250px;
object-fit: cover;
display: block;
}
.gallery-item figcaption {
padding: 1rem;
text-align: center;
font-weight: 600;
color: #333;
}
Key features:
object-fit: cover ensures images fill their space without distortionOn very small screens, adjust the layout for better mobile viewing:
@media (max-width: 600px) {
.gallery {
grid-template-columns: 1fr;
padding: 1rem;
}
.gallery-item img {
height: 200px;
}
}
This changes the gallery to a single column on small screens and reduces image height slightly.
This gallery combines several important concepts:
<figure> and <figcaption> for meaningful structureobject-fit: cover maintains uniform dimensionsYou can expand this gallery by adding more images, creating lightbox functionality with JavaScript, or implementing different grid patterns.
Create a simple photo blog post page that includes:
max-width: 100%)<figure> element with <figcaption> for at least one imageimages/ folder and practice using correct relative pathsAfter creating your page:
Images are an essential part of web development, helping to communicate ideas, create visual interest, and enhance user experience. The <img> tag requires two critical attributes: src to specify the image location, and alt to provide accessible alternative text.
Understanding file paths is crucial for displaying images correctly - whether using relative paths within your site, absolute paths from the root, or external URLs. Writing effective alt text makes your images accessible to users with screen readers and provides fallback information when images don't load.
Different image formats serve different purposes: JPEG for photographs, PNG for graphics with transparency, SVG for scalable icons and logos, and GIF for simple animations. Choosing the right format balances visual quality with file size and performance.
Images can be sized using HTML attributes or CSS properties, with CSS providing more flexibility and control. Making images responsive with max-width: 100% and height: auto ensures they work across all devices. Positioning techniques like float, Flexbox, and CSS Grid allow you to create sophisticated image layouts.
max-width: 100% at minimumWith a solid understanding of how to work with images, you're ready to learn about links in Lesson 10. Links and images often work together - for example, making images clickable or creating navigation with icon buttons. The next lesson will show you how to create effective navigation and connect your pages together.
Mozilla Developer Network. "The Image Embed element." MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
W3C Web Accessibility Initiative. "Images Tutorial." Web Accessibility Tutorials. https://www.w3.org/WAI/tutorials/images/
Mozilla Developer Network. "Responsive images." MDN Web Docs. https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
WebAIM. "Alternative Text." WebAIM. https://webaim.org/techniques/alttext/