Images are a vital part of modern web design. Whether you’re showcasing products, adding decorative visuals, or creating dynamic backgrounds, CSS makes it easy to style and control images on your website.
In this blog, you’ll learn how to add and manage images using CSS, including how to use them as backgrounds, style them, and enhance responsiveness.
✅ Method 1: Add Image in HTML and Style with CSS
The most common way to add an image is through HTML, then style it using CSS.
🔹 HTML:
<img src="image.jpg" alt="Sample Image" class="styled-image">
🔹 CSS:
.styled-image {
width: 100%;
max-width: 400px;
height: auto;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
width: 100%
andmax-width
make the image responsive.border-radius
rounds the corners.box-shadow
adds depth.
✅ Method 2: Add Image as a Background Using CSS
Sometimes you don’t want an <img>
tag. Instead, you can use an image as a background for a <div>
.
🔹 HTML:
<div class="background-box">
<h2>Text Over Image</h2>
</div>
🔹 CSS:
.background-box {
background-image: url('banner.jpg');
background-size: cover;
background-position: center;
height: 300px;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
Common properties:
Property | What It Does |
---|---|
background-image | Sets the image |
background-size | Controls scaling (cover , contain ) |
background-position | Aligns the image inside the element |
background-repeat | Prevents repetition (no-repeat ) |
✅ Method 3: Add Image Using CSS content
(Advanced)
For purely decorative images in pseudo-elements:
🔹 CSS:
.decorative::before {
content: url('icon.png');
margin-right: 10px;
}
Best used for icons or symbols that don’t need semantic meaning.
✨ Bonus: Tailwind CSS Example
<img src="photo.jpg" alt="Example" class="rounded-lg shadow-md w-full max-w-sm">
Tailwind provides utility classes to style and scale images without writing custom CSS.
✅ Summary
Task | Method |
---|---|
Add inline image | <img> tag with CSS styling |
Use image as a background | background-image in CSS |
Decorative image via CSS only | ::before with content: url() |
Make image responsive | max-width , width , height: auto |
Conclusion
Adding images in CSS allows for a high degree of visual control and flexibility. Whether you’re styling <img>
tags or applying images as backgrounds, CSS provides powerful tools to make your website look clean and professional.
Always remember to optimize your image files for faster loading and better performance.