β¬… 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

🟦 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
πŸ‘‰ Here is good example and image presentation of object fit

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