HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcssTip

How can I fit an image in a container with CSS?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
howwithcsscancontainerfitimage

Problem

Have you ever wanted to fit an image inside a container while preserving its aspect ratio? This is a common requirement when working with images, and it can be achieved using the object-fit and object-position properties in CSS.
Generally, you can use object-fit: contain to fit the entire image within the container while preserving its aspect ratio. On the other hand, object-fit: cover will fill the container with the image while preserving its aspect ratio.
You can also use object-position to position the image within the container. For example, object-position: center will center the image, while object-position: right top will position it at the top right corner.
https://codepen.io/chalarangelo/pen/KKOwRRZ

Solution

.image-contain {
  object-fit: contain;
  object-position: center;
}

.image-cover {
  object-fit: cover;
  object-position: right top;
}


You can also use object-position to position the image within the container. For example, object-position: center will center the image, while object-position: right top will position it at the top right corner.
https://codepen.io/chalarangelo/pen/KKOwRRZ

Code Snippets

.image-contain {
  object-fit: contain;
  object-position: center;
}

.image-cover {
  object-fit: cover;
  object-position: right top;
}

Context

From 30-seconds-of-code: fit-image-in-container

Revisions (0)

No revisions yet.