Object fit position
Author: g | 2025-04-24
Tutorial CSS object fit (object-fit) dan object position (object-position)
css - object-fit, object-positioning and absolute positioning -
A smaller size.Here’s a demo of how all values of object-fit work when applied to the same image. I’ve also added a green background to the images to show the container.See the Pen css object fit: object fit examples 1 by HubSpot (@hubspot) on CodePen.Here’s another example with a taller image:See the Pen css object fit: object fit examples 2 by HubSpot (@hubspot) on CodePen.And, as noted before, object-fit can also be applied to elements in addition to elements.CSS object-positionIf you’re going to use the object-fit property, it’s also useful to know about the object-position property. This property sets the position of the image inside of its container, which is useful if an image is cropped from resizing.Notice that, in the previous examples, the resized images are all centered inside of their containers. This is the default behavior of the browser, but you can overwrite this with object-position.object-position also targets the (or ) tag and takes one position value consisting of 2 numbers. The first specifies the position of the image on the x-axis and the second specifies its position on the y-axis. Each of these numbers can be a percentage or pixel value. They can also be a string: left, right, or center. The default value is 50% 50%, which centers the image in its container.Here’s an example of an image that has been resized with object-fit: cover with the image set to different positions:See the Pen css object fit: object position by HubSpot (@hubspot) on CodePen.CSS object-fit ExampleOne of the most common scenarios you’ll see object-fit being used is in image grids, in which each image needs to be the same size. In these cases, you can use object-fit to resize images of different sizes to fit in equal-sized boxes without warping the images.See the Pen css object fit: grid example by HubSpot (@hubspot) on CodePen.Make your images look professional with CSS.Personally, working through the process of implementing “object-fit” reminded me of arranging photos in a photo album. Just as you would carefully adjust each picture to fit neatly within its allotted space while keeping the essence of the image intact, “object-fit” lets you achieve similar harmony in web design.Now, it’s time for you to start building. 3.2.4 • Public • Published 7 years ago ReadmeCode Beta0 Dependencies131 Dependents44 Versionsobject-fit-images 🗻 Polyfill object-fit/object-position on : IE9, IE10, IE11, Edge, Safari, ...Fast and lightweight (demo)No additional elements are createdSetup is done via CSSScaling is taken care by the browser (it uses background-size)srcset supportsrc and srcset properties and attributes keep working: img.src = 'other-image.jpg'Alternative solutionsComparisonbfred-it/object-fit-images🌟constancecchen/object-fit-polyfilltonipinel/object-fit-polyfillBrowsersIEdge 9-14, Android"All browsers"Tagsimgimage video pictureimgcover/contain💚💚💚fill💚💚💚none💚💚💚scale-down💚 using {watchMQ:true}💚💔object-position💚💚💔srcset support💚 Native or picturefill notes💚💔Extra elements💚 No💔 Yes💔 YesSettings💚 via CSS💔 via HTML💔 via HTMLUsageYou will need 3 thingsone or more elements with src or srcsetimg class='your-favorite-image' src='image.jpg'>CSS defining object-fit and a special font-family property to allow IE to read the correct value.your-favorite-image { object-fit: contain; font-family: 'object-fit: contain;';}or, if you also need object-position.your-favorite-image { object-fit: cover; object-position: bottom; font-family: 'object-fit: cover; object-position: bottom;';}To generate the font-family automatically, you can use the PostCSS plugin or the SCSS/SASS/Less mixins.If you set the font-family via JavaScript (which must be followed by calling objectFitImages()), make sure to include the quotes in the property. the activation call before , or on DOM readyThis will fix all the images on the page and also all the images added later (auto mode).Alternatively, only fix the images you want, once:objectFitImages('img.some-image');var someImages = document.querySelectorAll('img.some-image');objectFitImages(someImages);var oneImage = document.querySelector('img.some-image');objectFitImages(oneImage);var $someImages = $('img.some-image');objectFitImages($someImages);You can call objectFitImages() on the same elements more than once without issues, for example to manually request an update of the object-fit value.Apply on resizeYou don't need to re-apply it on resize, unless:You're using scale-down, oryour media queries change the value of object-fit, like this img { object-fit: cover; }@media (max-width: 500px) { img { object-fit: contain; } }In one of those cases, use the watchMQ option:objectFitImages('img.some-image', {watchMQ: true});InstallPick your favorite:script src="dist/ofi.min.js">/script>npm install --save object-fit-imagesvar objectFitImages = require('object-fit-images');import objectFitImages from 'object-fit-images';APIobjectFitImages(images, options)Both parameters are optional. parameter description images Type: string, element, array, NodeList, null Default:object-fit and object-position - Hyperskill
Example, you can handle the image cropping on the server-side using PHP or some JavaScript script, and then serve the cropped image on the site. You may even be in a different scenario, where you just want to be able to quickly crop and display the images on a page, without using a CMS and back-end script.Fortunately, today, CSS has two properties that make cropping and scaling images within a fitted box a breeze. These properties are object-fit and object-position.The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.Even though a bitmap image has its own intrinsic dimensions and aspect ratio, you can size it to fit into any box of any size as defined in your CSS. And you can choose whether you want to preserve the aspect ratio of the image or not, all using one property (object-fit) and one line of CSS.The following image shows the effect of each of the possible values for object-fit: The result of applying the different object-fit values to an image to be fitted in a box with a different aspect ratio. By default, the image is centered within its containing box (the square, in our example). You can change that default position using object-position, which takes values similar to the values of background-position. For example, object-position: top left will align the top edge of the image to the top border of the box, and the left edge of the image to the left border of the box. Here’s a live Codepen for you to try the effect of changing object-position on the images:See the Pen CSS `object-fit` Values by Sara Soueidan (@SaraSoueidan) on CodePen.Browser support for object-fit and object-position is very good: it is supported in all the latest browsers, including MS Edge 16+ and Opera Mini, though it requires the -o- prefix in the latter. You can see the latest updated browser support on CanIUse.com.If you, like me, want to be able to provide a similar experience to Internet Explorer, you’re going to need an alternative solution, or at least a fallback. And, ideally, the alternative solution needs to provide support at least back to IE9, maybe? This is where SVG can fill in.Cropping & Scaling Images with SVGIf you’ve ever played with the SVG viewBox, then you know that the coordinate system defined by the viewBox does not necessarily need to have the same aspect ratio as that of the viewport.And when the aspect ratio of the viewBox is not the same as that of the viewport, the browser needs to position the former in the latter similar to the way the photo was being. Tutorial CSS object fit (object-fit) dan object position (object-position)CSS object-fit and object-position
Positioned inside the box in the previous section.By default, just like with object-fit, the browser will fit the viewBox inside of the SVG viewport (or “box”) by containing it inside of it, such that the entire viewBox — and, thus, all the contents of the SVG — are visible inside the viewport.Using the preserveAspectRatio attribute, you can change the position and scale of the viewBox — and, thus, all the contents of the SVG — similar to the way object-position changes the position and scale of the image inside the box when using object-fit.For example, suppose we have a square svg (aspect ratio 1:1) and a viewBox that has a different aspect ratio (2:1). The easiest and fastest way to visualize the viewBox coordinate system in the svg is to create a that starts at the coordinate system’s origin and has a width and height value of 100%.svg width="300px" height="300px" viewBox="0 0 500 250"> rect x="0" y="0" width="100%" height="100%" fill="#FEDA00">rect>svg>The result of the above code is shown in the image below. The yellow rectangle represent the size and position of the viewBox within the svg viewport. The result of applying the different object-fit values to an image to be fitted in a box with a different aspect ratio. Now, using preserveAspectRatio, you can change the position of the viewBox as well as its size (or scale) within the viewport similar to the same way we could change the position and scale of our image in the previous section using object-fit and object-position.A preserveAspectRatio value is made up of two keywords, one of them represents the scale viewBox and has one of two values: meet or slice.meet has the same effect as object-fit: contain; (or background-size: contain;) and slice has the same effect as object-fit: cover; (or background-size: cover;). The former will preserve the aspect ratio of the viewBox and fit it inside the viewport so that it’s entirely visible. This is the default behavior. Whereas slice will scale the viewBox up, while preserving its aspect ratio, so that it covers the entire viewport area, even if it means cutting some of the content off (hence the “slicing” effect).The other keyword in preserveAspectRatio represents and controls the position of the viewBox within the viewport. It has 19 values, including none which tells the browser to scale the viewBox to fill the viewport area without preserving its aspect ratio, and is similar in effect to object-fit: fill;.The default value for the preserveAspectRatio is xMidYMid meet, which is the value the browser uses even if you completely omit the attribute from the .The following snippet using preserveAspectRatio="xMinYMin meet will change the position of the viewBox in the previous example such that the yellow { width: 100%; height: 100%; object-fit: contain;}3. Shift images with object-positionSimilarly to the complementing background-position property of background-size, there’s an object-position property for object-fit, too.The object-fit property moves an image inside an image container to the given coordinates. The coordinates can be defined as absolute length units, relative length units, keywords (top, left, center, bottom, and right), or a valid combination of them(top 20px right 5px, center right 80px). #container { width: 300px; height: 300px;}img { width: 100%; height: 100%; object-position: 150px 0;}4. Situate images with vertical-alignWe sometimes add (which are inline by nature) next to text strings for added information or decoration. In that case, aligning the text and the image into the desired position can be a tad bit tricky—if you don’t know which property to use.The vertical-align property is not exclusive to table cells alone. It can also align an inline element inside an inline box, and thus can be used to align an image in a line of text. It takes a fair number of values that can be applied to an inline element, so you have many options to choose from.PDF 5. Shadow images with filter: drop-shadow()When used inconspicuously in texts and boxes, shadows can add life to a web page. The same is true for in images. Images with core shapes and transparent backgrounds can benefit from the drop-shadow CSS filter.Its arguments are similar to the values of the shadow-related CSS properties (text-shadow, box-shadow). The first two represent the vertical and horizontal distance between the shadows and the image, the third and fourth are the blur and the spread radius of the shadow, and the last one is the shadow color.Just like text-shadow, drop-shadow also creates a shadow that is molded to the belonging object. So, when it’s applied to an image, the shadow takes the shape of the visible portion of the image.img { filter: drop-shadow(0 0 5px blue);}Read Also: CSS3 Image Reflection [CSS3 Tips]">css - object-fit, object-positioning and absolute positioning - Stack
Of SVG further, add a couple of attributes on the element to describe the role of the as well as re-enforce the relationship between the and the element, so that the latter is recognised by screen readers as the accessible name for the SVG content (—our image, in this case).svg width="300px" height="300px" viewBox="0 0 579 375" preserveAspectRatio="xMidYMid meet" aria-labelledby="title" aria-role="img"> title id="title">Painter’s Handstitle> image xlink:href=" x="0" y="0" width="100%" height="100%">image> svg>And just like that, you now have a perfectly accessible SVG alternative to a CSS object-fit declaration.Summary & RecapYou can crop and scale any image using CSS object-fit and object-position. However, these properties are only supported in the latest version of ME Edge as well as all other modern browsers.If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an , and using the viewBox and preserveAspectRatio attributes to do what object-fit and object-position do.The snippet can replace an object-fit declaration:svg width="x" height="y" viewBox="0 0 imgX imgY" preserveAspectRatio=" ” aria-labelledby="title" aria-role="img"> title id="title"> img alt here &ly/title> image xlink:href="..." width="100%" height=“100%”> image>svg>where imgX and imgY are the dimensions of the image you want to crop and scale, and and are the two keywords that determine the scale and position of the image within the SVG wrapper.And that’s it. A simple SVG tip to provide better cross-browser support for a less-supported CSS feature.I hope you like this tip and find it useful. Thank you for reading! Join my mailing list Every 2–3 weeks, I send out an email newsletter with useful exclusive content, insider tips, links, resources, and latest updates on design engineering — from my own work as well as the work and articles created by smart people in the Web community. Subscribe to get the newsletter in your email inbox. 📥Object Fit dan Object Position CSS
In this article, I would like to present how to resize an image to fit a HTML container.The most popular approach is to add object-fit property to img tag, we will use it as well, plus we will add other CSS properties.To get things done we will use this CSS selectors and properties..project { display: flex; margin: 50px 0;}.project__image { flex: 1;}.project__image--relative { position: relative; }.project__image--background-img { background: url(' background-position: center; background-size: cover; background-repeat: no-repeat;}.project__image img { width: 100%; height: 400px; object-fit: cover; object-position: center;}.project__image--relative img { position: absolute; height: 100%;}.project__description { flex: 1; margin: 0; padding: 20px; align-self: center;}In the following examples, we will change HTML and CSS structure to achieve our goal.Example 1 - background imageclass="project"> div class="project__image project__image--background-img">div> p class="project__description"> Image description Received the likewise law graceful his. Nor might set along charm now equal green. Pleased yet equally correct colonel not one. Say anxious carried compact conduct sex general nay certain. Mrs for recommend exquisite household eagerness preserved now. My improved honoured he am ecstatic quitting greatest formerly. Examine she brother prudent add day ham. Far stairs now coming bed oppose hunted become his. You zealously departure had procuring suspicion. Books whose front would purse if be do decay. Quitting you way formerly disposed perceive ladyship are. Common turned boy direct and yet. p>div>As you can see we have no img tag in this example. We use background image with background-size: cover to resize the background image and make sure the image is fully visible.Example 2 - nested img element and object-fit: cover propertyclass="project"> div class="project__image"> img src=" alt="example image"> div> p class="project__description"> Image description Received the likewise law graceful his. Nor might set along charm now equal green. Pleased yet equally correct colonel not one. Say anxious carried compact conduct sex general nay certain. Mrs for recommend exquisite household eagerness preserved now. My improved honoured he am ecstatic quitting greatest formerly. Examine she brother prudent add day ham. Far stairs now coming bed oppose hunted become his. You zealously departure had procuring suspicion. Books whose front would purse if be do decay. Quitting you way. Tutorial CSS object fit (object-fit) dan object position (object-position) Tutorial CSS object fit (object-fit) dan object position (object-position)CSS object-fit and object-position - CodePen
Imagine you have a frame for a picture, but the picture doesn‘t fit perfectly inside the frame. Maybe it’s too tall, or too wide. In this case, you’d fold or trim the photo so it fits properly.In CSS, you’ll probably come across a similar issue with images, and the object-fit property is the solution — it’s like telling the picture how it should behave within that frame.In this post, we’ll show you when and how to use it to make your images and image grids look as professional as they can be. Plus, we’ll also see how the object-position property can be used in conjunction with object-fit. Let’s dive in.What is object-fit in CSS?Image sizing can be tricky in HTML. Say you have an image that you want to give a specific width and height. When rendering the HTML, the browser first creates a container for the image with the specified dimensions. Then, it adds the image into the container and stretches the image to fit the dimensions of the container.For example, the below code features one image that is 300 pixels by 200 pixels, and then the same image resized to 250 pixels by 250 pixels:See the Pen css object fit: stretch example by HubSpot (@hubspot) on CodePen.Because the image’s container changed and the aspect ratio of the original image is not preserved, the resized image looks oddly warped, and we don’t want that.Here’s where object-fit comes in. The CSS object-fit property tells the browser how to resize the image inside its container. Instead of stretching or squishing an image, object-fit proportionately changes the image. The final product is a properly sized photo without distortion.Before we continue, you may be wondering why the property is called “object”-fit and not “image”-fit. This is because this property can be used on any object in HTML. In HTML, an object is any external resource — in other words, a file that is not in the HTML. Most commonly, these are images or videos. For the purposes of this article, we’ll use images in our examples.CSS object-fit Valuesobject-fit can take one of five values:fill: The image resizes to fill its container, stretching and/or squashing if necessary. This is the default value and what happens if object-fit is not defined.contain: The image keeps its aspect ratio and is scaled to fit its container. The entire image will be visible, even if it doesn’t fill the entire container.cover: The image keeps its aspect ratio and is scaled to fill the entire container. This may result in the image being clipped.none: The image is displayed at its original size, regardless of the container's dimensions.scale-down: The image is scaled down to either contain or none, whichever isComments
A smaller size.Here’s a demo of how all values of object-fit work when applied to the same image. I’ve also added a green background to the images to show the container.See the Pen css object fit: object fit examples 1 by HubSpot (@hubspot) on CodePen.Here’s another example with a taller image:See the Pen css object fit: object fit examples 2 by HubSpot (@hubspot) on CodePen.And, as noted before, object-fit can also be applied to elements in addition to elements.CSS object-positionIf you’re going to use the object-fit property, it’s also useful to know about the object-position property. This property sets the position of the image inside of its container, which is useful if an image is cropped from resizing.Notice that, in the previous examples, the resized images are all centered inside of their containers. This is the default behavior of the browser, but you can overwrite this with object-position.object-position also targets the (or ) tag and takes one position value consisting of 2 numbers. The first specifies the position of the image on the x-axis and the second specifies its position on the y-axis. Each of these numbers can be a percentage or pixel value. They can also be a string: left, right, or center. The default value is 50% 50%, which centers the image in its container.Here’s an example of an image that has been resized with object-fit: cover with the image set to different positions:See the Pen css object fit: object position by HubSpot (@hubspot) on CodePen.CSS object-fit ExampleOne of the most common scenarios you’ll see object-fit being used is in image grids, in which each image needs to be the same size. In these cases, you can use object-fit to resize images of different sizes to fit in equal-sized boxes without warping the images.See the Pen css object fit: grid example by HubSpot (@hubspot) on CodePen.Make your images look professional with CSS.Personally, working through the process of implementing “object-fit” reminded me of arranging photos in a photo album. Just as you would carefully adjust each picture to fit neatly within its allotted space while keeping the essence of the image intact, “object-fit” lets you achieve similar harmony in web design.Now, it’s time for you to start building.
2025-04-013.2.4 • Public • Published 7 years ago ReadmeCode Beta0 Dependencies131 Dependents44 Versionsobject-fit-images 🗻 Polyfill object-fit/object-position on : IE9, IE10, IE11, Edge, Safari, ...Fast and lightweight (demo)No additional elements are createdSetup is done via CSSScaling is taken care by the browser (it uses background-size)srcset supportsrc and srcset properties and attributes keep working: img.src = 'other-image.jpg'Alternative solutionsComparisonbfred-it/object-fit-images🌟constancecchen/object-fit-polyfilltonipinel/object-fit-polyfillBrowsersIEdge 9-14, Android"All browsers"Tagsimgimage video pictureimgcover/contain💚💚💚fill💚💚💚none💚💚💚scale-down💚 using {watchMQ:true}💚💔object-position💚💚💔srcset support💚 Native or picturefill notes💚💔Extra elements💚 No💔 Yes💔 YesSettings💚 via CSS💔 via HTML💔 via HTMLUsageYou will need 3 thingsone or more elements with src or srcsetimg class='your-favorite-image' src='image.jpg'>CSS defining object-fit and a special font-family property to allow IE to read the correct value.your-favorite-image { object-fit: contain; font-family: 'object-fit: contain;';}or, if you also need object-position.your-favorite-image { object-fit: cover; object-position: bottom; font-family: 'object-fit: cover; object-position: bottom;';}To generate the font-family automatically, you can use the PostCSS plugin or the SCSS/SASS/Less mixins.If you set the font-family via JavaScript (which must be followed by calling objectFitImages()), make sure to include the quotes in the property. the activation call before , or on DOM readyThis will fix all the images on the page and also all the images added later (auto mode).Alternatively, only fix the images you want, once:objectFitImages('img.some-image');var someImages = document.querySelectorAll('img.some-image');objectFitImages(someImages);var oneImage = document.querySelector('img.some-image');objectFitImages(oneImage);var $someImages = $('img.some-image');objectFitImages($someImages);You can call objectFitImages() on the same elements more than once without issues, for example to manually request an update of the object-fit value.Apply on resizeYou don't need to re-apply it on resize, unless:You're using scale-down, oryour media queries change the value of object-fit, like this img { object-fit: cover; }@media (max-width: 500px) { img { object-fit: contain; } }In one of those cases, use the watchMQ option:objectFitImages('img.some-image', {watchMQ: true});InstallPick your favorite:script src="dist/ofi.min.js">/script>npm install --save object-fit-imagesvar objectFitImages = require('object-fit-images');import objectFitImages from 'object-fit-images';APIobjectFitImages(images, options)Both parameters are optional. parameter description images Type: string, element, array, NodeList, null Default:
2025-04-15Example, you can handle the image cropping on the server-side using PHP or some JavaScript script, and then serve the cropped image on the site. You may even be in a different scenario, where you just want to be able to quickly crop and display the images on a page, without using a CMS and back-end script.Fortunately, today, CSS has two properties that make cropping and scaling images within a fitted box a breeze. These properties are object-fit and object-position.The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.Even though a bitmap image has its own intrinsic dimensions and aspect ratio, you can size it to fit into any box of any size as defined in your CSS. And you can choose whether you want to preserve the aspect ratio of the image or not, all using one property (object-fit) and one line of CSS.The following image shows the effect of each of the possible values for object-fit: The result of applying the different object-fit values to an image to be fitted in a box with a different aspect ratio. By default, the image is centered within its containing box (the square, in our example). You can change that default position using object-position, which takes values similar to the values of background-position. For example, object-position: top left will align the top edge of the image to the top border of the box, and the left edge of the image to the left border of the box. Here’s a live Codepen for you to try the effect of changing object-position on the images:See the Pen CSS `object-fit` Values by Sara Soueidan (@SaraSoueidan) on CodePen.Browser support for object-fit and object-position is very good: it is supported in all the latest browsers, including MS Edge 16+ and Opera Mini, though it requires the -o- prefix in the latter. You can see the latest updated browser support on CanIUse.com.If you, like me, want to be able to provide a similar experience to Internet Explorer, you’re going to need an alternative solution, or at least a fallback. And, ideally, the alternative solution needs to provide support at least back to IE9, maybe? This is where SVG can fill in.Cropping & Scaling Images with SVGIf you’ve ever played with the SVG viewBox, then you know that the coordinate system defined by the viewBox does not necessarily need to have the same aspect ratio as that of the viewport.And when the aspect ratio of the viewBox is not the same as that of the viewport, the browser needs to position the former in the latter similar to the way the photo was being
2025-04-23Positioned inside the box in the previous section.By default, just like with object-fit, the browser will fit the viewBox inside of the SVG viewport (or “box”) by containing it inside of it, such that the entire viewBox — and, thus, all the contents of the SVG — are visible inside the viewport.Using the preserveAspectRatio attribute, you can change the position and scale of the viewBox — and, thus, all the contents of the SVG — similar to the way object-position changes the position and scale of the image inside the box when using object-fit.For example, suppose we have a square svg (aspect ratio 1:1) and a viewBox that has a different aspect ratio (2:1). The easiest and fastest way to visualize the viewBox coordinate system in the svg is to create a that starts at the coordinate system’s origin and has a width and height value of 100%.svg width="300px" height="300px" viewBox="0 0 500 250"> rect x="0" y="0" width="100%" height="100%" fill="#FEDA00">rect>svg>The result of the above code is shown in the image below. The yellow rectangle represent the size and position of the viewBox within the svg viewport. The result of applying the different object-fit values to an image to be fitted in a box with a different aspect ratio. Now, using preserveAspectRatio, you can change the position of the viewBox as well as its size (or scale) within the viewport similar to the same way we could change the position and scale of our image in the previous section using object-fit and object-position.A preserveAspectRatio value is made up of two keywords, one of them represents the scale viewBox and has one of two values: meet or slice.meet has the same effect as object-fit: contain; (or background-size: contain;) and slice has the same effect as object-fit: cover; (or background-size: cover;). The former will preserve the aspect ratio of the viewBox and fit it inside the viewport so that it’s entirely visible. This is the default behavior. Whereas slice will scale the viewBox up, while preserving its aspect ratio, so that it covers the entire viewport area, even if it means cutting some of the content off (hence the “slicing” effect).The other keyword in preserveAspectRatio represents and controls the position of the viewBox within the viewport. It has 19 values, including none which tells the browser to scale the viewBox to fill the viewport area without preserving its aspect ratio, and is similar in effect to object-fit: fill;.The default value for the preserveAspectRatio is xMidYMid meet, which is the value the browser uses even if you completely omit the attribute from the .The following snippet using preserveAspectRatio="xMinYMin meet will change the position of the viewBox in the previous example such that the yellow
2025-04-17