CSS
CSS: How to Add an Image to Your Web Page
Images are an essential part of web design. They help enhance visual appeal, support content, and improve user experience. While HTML is used to place images on a page, CSS can help control how and where those images appear—either as content or as background.
In this post, you’ll learn:
- ✅ How to insert images using HTML
- ✅ How to use CSS to style images
- ✅ How to add images as backgrounds
- 🧪 Practical code examples
✅ 1. Inserting an Image Using HTML
This is the standard way to display an image on a web page:
✅ HTML:
<img src="image.jpg" alt="A descriptive text" class="main-image">
✅ CSS (Styling the Image):
.main-image {
width: 300px;
height: auto;
border: 2px solid #ccc;
border-radius: 8px;
}
✅ This displays and styles the image using CSS for size, borders, and more.
🎨 2. Adding an Image as a Background Using CSS
You can also add images as backgrounds to divs or other HTML elements.
✅ CSS:
.hero-banner {
background-image: url('banner.jpg');
background-size: cover;
background-position: center;
width: 100%;
height: 400px;
}
✅ HTML:
<div class="hero-banner"></div>
🧠 Use this method when the image is purely decorative or part of the design layout.
🔄 3. CSS Background Image Properties
Here are some commonly used background-image properties:
Property | Description |
---|---|
background-image | Adds the image |
background-size | cover , contain , or specific dimensions |
background-repeat | Prevents or allows repetition |
background-position | Sets alignment (e.g., center , top right ) |
background-attachment | Controls scroll behavior (fixed , scroll ) |
🧪 Example: Fullscreen Background
.fullscreen-bg {
background-image: url('background.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 100vh;
}
HTML:
<div class="fullscreen-bg"></div>
📌 This creates a full-page background section using an image.
🧠 Best Practices for Using Images in CSS
Best Practice | Why It Matters |
---|---|
Use alt tags for <img> | Accessibility and SEO |
Optimize image size | Faster page load times |
Use modern formats (e.g. WebP) | Smaller file size without quality loss |
Set dimensions in CSS | Prevent layout shifts and improve layout |
🧠 Summary
Goal | Use This |
---|---|
Insert visible image | <img> tag + CSS for styling |
Decorative image/design | background-image in CSS |
Responsive scaling | Use background-size: cover or width: 100% |
Image control via CSS | Use properties like border , padding , etc. |
🏁 Final Thoughts
Adding and styling images with CSS allows you to create visually engaging and responsive layouts. Whether you’re inserting a photo, decorating a background, or designing a hero section, combining HTML and CSS gives you full control.