This site is mobile accessible. Press the "Tap Here" button to use a smaller font-size.
Smartphone icons created by Freepik - Flaticon
The CSS
property is used to specify how an <img> or <video> should be resized to fit its container.The CSS
property is used to specify how an <img> or <video> should be resized to fit its container. This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible". Look at the following image from Paris. This image is 400 pixels wide and 300 pixels high:However, if we style the image above to be half its width (200 pixels) and same height (300 pixels), it will look like this:
img { width: 200px; height: 300px; }
We see that the image is being squished to fit the container of 200x300 pixels (its original aspect ratio is destroyed). Here is where the
property comes in. The property can take one of the following values:If we use
the image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit:img { width: 200px; height: 300px; object-fit: cover;
If we use
the image keeps its aspect ratio, but is resized to fit within the given dimension:img { width: 200px; height: 300px; object-fit: contain; }
If we use
the image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit:img { width: 200px; height: 300px; object-fit: fill; }
If we use object-fit: none; the image is not resized:
img { width: 200px; height: 300px; object-fit: none; }
If we use
the image is scaled down to the smallest version of or :img { width: 200px; height: 300px; object-fit: scale-down; }
Here we have two images and we want them to fill the width of 50% of the browser window and 100% of the height. In the following example we do NOT use
, so when we resize the browser window, the aspect ratio of the images will be destroyed:In the next example, we use
, so when we resize the browser window, the aspect ratio of the images is preserved:The following example demonstrates all the possible values of the
property in one example:.fill {object-fit: fill;} .contain {object-fit: contain;} .cover {object-fit: cover;} .scale-down {object-fit: scale-down;} .none {object-fit: none;}
The following table lists the CSS object-* properties:
Property | Description |
---|---|
object-fit | Specifies how an <img> or <video> should be resized to fit its container |
object-position | Specifies how an <img> or <video> should be positioned with x/y coordinates inside its "own content box" |