πΌοΈ Images in CSS β Complete Guide
1. π Images are inline elements
By default, the <img> tag is an inline element.
π This means:
- it has horizontal spacing (like text)
- it has a bottom gap (baseline space)
β Problem:
- this bottom gap looks like an unwanted empty space
- it breaks layouts
- it is almost never needed
2. β How to remove the bottom gap
π Solution β make the image a block element:
img {
display: block;
}
β Result:
- bottom gap disappears
- layout becomes stable
- this is standard practice
3. π Responsive (βfluidβ) images
β Problem:
- without CSS, images keep their original size
- they can overflow their container
β Solution:
img {
display: block;
max-width: 100%;
}
β What this does:
- image shrinks to fit the container
- never becomes larger than original size
- keeps quality
π 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:
- container has one size
- image has different proportions
β Property:
object-fit: value;
π Main values
1. fill (default)
- stretches image
- β distorts it
2. contain
- keeps proportions
- shows full image
- β leaves empty space
3. β
cover (most important)
- keeps proportions
- fills container
- crops excess parts
π cover is most commonly used
4. none
- original size
- ignores container
5. scale-down
- picks smaller of
noneorcontain
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:
- all images same size
- no distortion
- looks like e-commerce cards
6. π Global styles (best practice)
π In real projects always use:
img {
display: block;
max-width: 100%;
}
β Why:
- no repeated code
- no layout bugs
- all images responsive
7. π§© Common mistakes
- β Forget
display: blockβ bottom gap appears - β Use
width: 100%β image stretches and loses quality - β No container height β
object-fitwonβt work - β No
height: 100%on img β image doesnβt fill container
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:
- e-commerce websites π
- blogs π°
- galleries πΌοΈ
- product cards π¦
π Want next step?
I can give you:
- β real junior frontend tasks
- β interview-style questions
- β mini project (product cards layout)