← Back to CSS Course | Chapter 8: Animations & Effects | Lesson 10 of 22

CSS Image Styling

An <img> tag on its own is just a raw rectangle of pixels — CSS is what gives it rounded corners, a border, a drop shadow, a filter effect, and the ability to resize gracefully with its container.

Rounding Image Corners

Applying border-radius to an <img> works exactly like it does on any other box, rounding the image's corners or, at 50%, turning a square image into a perfect circle. Because the image itself is clipped to the rounded box, no extra masking property is needed for this simple case.

Example: Rounding Image Corners

css
<style>
img {
  border-radius: 50%;
}
</style>
<img src="https://placehold.co/100x100" alt="Circular image">

Borders and Shadows on Images

A regular border property draws a frame around an image just as it would around a div, and box-shadow adds a drop shadow behind it — combining both is a common way to make a photo look like a printed card sitting above the page.

Example: Borders and Shadows on Images

css
<style>
img {
  border: 4px solid white;
  box-shadow: 0 4px 10px rgba(0,0,0,0.3);
}
</style>
<img src="https://placehold.co/150x100" alt="Framed like a printed card">

Filter Effects on Images

The filter property applies effects like grayscale(), blur(), brightness(), and sepia() directly to an image's pixels without needing an image editor, and these filters can be combined and even transitioned smoothly on hover.

Example: Filter Effects on Images

css
<style>
img {
  filter: grayscale(100%);
  transition: filter 0.3s;
}
img:hover {
  filter: none;
}
</style>
<img src="https://placehold.co/150x100" alt="Grayscale, hover to see color">

Responsive Images with max-width

Setting max-width: 100% (with height: auto) on an image lets it shrink to fit its container on small screens while never stretching wider than its natural size, which is the single most common responsive-image rule on the web.

Example: Responsive Images with max-width

css
<style>
img {
  max-width: 100%;
  height: auto;
}
</style>
<img src="https://placehold.co/1200x600" alt="Shrinks but never grows past natural size">

object-fit for Cropped Images

When an image doesn't match its container's aspect ratio, object-fit: cover crops it to fill the box without distorting it, while object-fit: contain shrinks it to fit entirely inside the box, leaving empty space if needed.

Example: object-fit for Cropped Images

css
<style>
.cover {
  width: 150px;
  height: 100px;
  object-fit: cover;
}
.contain {
  width: 150px;
  height: 100px;
  object-fit: contain;
}
</style>
<img class="cover" src="https://placehold.co/400x200" alt="Cropped to fill">
<img class="contain" src="https://placehold.co/400x200" alt="Shrunk to fit entirely">

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.