0
0
CssHow-ToBeginner · 3 min read

How to Make Image Fit Container in CSS: Simple Guide

To make an image fit its container in CSS, use the width: 100% and height: 100% properties along with object-fit: cover or object-fit: contain. This ensures the image scales properly inside the container without distortion.
📐

Syntax

Use the following CSS properties on the <img> element:

  • width: 100% - makes the image width match the container's width.
  • height: 100% - makes the image height match the container's height.
  • object-fit - controls how the image scales inside the container:
    • cover: fills the container, cropping if needed.
    • contain: fits the whole image inside, may leave empty space.
css
img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* or contain */
}
💻

Example

This example shows an image inside a fixed-size container. The image fills the container fully without distortion using object-fit: cover.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Fit Container Example</title>
<style>
  .container {
    width: 300px;
    height: 200px;
    border: 2px solid #333;
    overflow: hidden;
  }
  .container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>
</head>
<body>
  <div class="container">
    <img src="https://via.placeholder.com/600x400" alt="Sample Image">
  </div>
</body>
</html>
Output
A 300px by 200px box with a border containing the image scaled and cropped to fill the box fully without distortion.
⚠️

Common Pitfalls

Common mistakes when fitting images inside containers include:

  • Not setting both width and height to 100%, causing the image to keep its original size.
  • Using object-fit without fixed container dimensions, so the container size collapses.
  • Using object-fit: cover when you want the whole image visible (use contain instead).
css
/* Wrong: image keeps original size */
.container img {
  width: 100%;
  /* height missing */
  object-fit: cover;
}

/* Right: image fills container */
.container {
  width: 300px;
  height: 200px;
}
.container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
📊

Quick Reference

Summary tips for fitting images inside containers:

  • Set container size explicitly (width and height).
  • Set image width and height to 100%.
  • Use object-fit: cover to fill and crop.
  • Use object-fit: contain to fit fully without cropping.
  • Use overflow: hidden on container to hide overflow if needed.

Key Takeaways

Always set both width and height of the image to 100% to fill the container.
Use object-fit: cover to fill the container and crop excess parts.
Use object-fit: contain to show the whole image without cropping.
Set fixed dimensions on the container to control image size.
Use overflow: hidden on the container to hide any overflow from cropping.