⬅ Back

🖼️ Images in CSS — Complete Guide

1. 📌 Images are inline elements

By default, the <img> tag is an inline element.

👉 This means:

❗ Problem:

2. ✅ How to remove the bottom gap

👉 Solution — make the image a block element:

img {
  display: block;
}
✔ Result:

3. 📐 Responsive (“fluid”) images

❗ Problem:
✅ Solution:
img {
  display: block;
  max-width: 100%;
}
Image with max-width 100% example
✔ What this does:

👉 This is called: responsive images

❗ Difference: max-width vs width

Video lesson: watch CSS width, min-width, and max-width explained on YouTube.

🟦 width: 100%

  • Always forces the element to be exactly 100% of the parent
  • Even if the content is smaller → it stretches
  • Can break layout or look weird

👉 Example:

  • Image is 200px
  • Parent is 400px
  • ➡️ Image becomes 400px (stretched)

🟩 max-width: 100%

  • Sets a maximum limit, not a fixed size
  • Element can be smaller, but never bigger than parent
  • Keeps original size if smaller

👉 Example:

  • Image is 200px
  • Parent is 400px
  • ➡️ Image stays 200px (no stretch)

👉 If image is 800px:

  • ➡️ It shrinks to 400px (fits safely)

4. 🧠 object-fit — controlling image inside a container

❗ Problem:
✅ Property:
object-fit: value;
🔑 Main values
1. fill (default)
2. contain
3. ✅ cover (most important)

👉 cover is most commonly used

4. none
5. scale-down

🖼️ See all values visually

Open this visual demonstration to compare fill, contain, cover, none, and scale-down using images:

👉 Open MDN's object-fit visual examples

For definitions and an interactive example, see the MDN object-fit reference.

5. 📦 Proper usage of object-fit

✔ HTML:
<div class="thumb">
  <img src="image.jpg" alt="">
</div>
✔ CSS:
.thumb {
  width: 300px;
  height: 400px;
}

.thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
✔ Result:

6. 🌍 Global styles (best practice)

👉 In real projects always use:

img {
  display: block;
  max-width: 100%;
}
✔ Why:

7. 🧩 Common mistakes

8. 🧠 Quick summary

👉 Always:

img {
  display: block;
  max-width: 100%;
}

👉 For cards:

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

🔥 Real-world usage

Used in:

🚀 Want next step?

I can give you:

⬅ Back