Skip to main content
Dublin Library

The Publishing Project

Object-fit and background-size

 

One very frustrating thing when working with images on the web is when you're trying to fit an image into a container. If the image has different dimensions and aspect ratio than the container, the image will be resized to fit, losing potentially important portions of the image or stretching it to the point it becomes blurry and hard to find the details on it. This post will discuss three attributes that may help solve this type of problem: `object-fit`, `background-size` and `aspect-ratio`. ## Background Before we start there are a couple of background items to talk about. ### Replaced Elements In the context of CSS, replaced elements are elements whose contents are not affected by the current document's styles. We can control the position of a replaced element (like using float to control the position of an image or video in relation to surrounding elements) but we can't control the content of the replaced element. However, you can style the fallback for replaced elements as shown in [Styling broken Images](https://bitsofco.de/styling-broken-images/) by [Ire Aderinokun](https://ireaderinokun.com/) These are some common replaced elements: * <iframe> * <video> * <embed> * <img> * <input type="image"> ## object-fit The `object-fit` property sets how the content of a replaced element, such as an `` or `