Convert Figma logo to code with AI

fregante logoobject-fit-images

🗻 Polyfill object-fit/object-position on <img>: IE9, IE10, IE11, Edge, Safari, ...

2,033
269
2,033
3

Top Related Projects

A responsive image polyfill for <picture>, srcset, sizes, and more

📱 Make videos playable inline on the iPhone (prevents automatic fullscreen)

17,454

High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.

JavaScript, SCSS, Sass, Less, and Stylus helpers for rendering high-resolution image variants

LazyLoad is a lightweight, flexible script that speeds up your website by deferring the loading of your below-the-fold images, backgrounds, videos, iframes and scripts to when they will enter the viewport. Written in plain "vanilla" JavaScript, it leverages IntersectionObserver, supports responsive images and enables native lazy loading.

:camera: JavaScript is all like "You images done yet or what?"

Quick Overview

The object-fit-images project is a lightweight JavaScript library that polyfills the object-fit and object-position CSS properties for browsers that don't natively support them. This allows developers to use these modern CSS features to control the sizing and positioning of images, even in older browsers.

Pros

  • Lightweight: The library is small in size, weighing in at just 1.5 KB (minified and gzipped).
  • Cross-browser Compatibility: It provides a solution for browsers that don't natively support object-fit and object-position.
  • Customizable: The library allows for various configuration options to fine-tune the behavior.
  • Performant: The library uses efficient techniques to minimize the impact on page load and rendering.

Cons

  • Dependency on JavaScript: The library requires JavaScript to be enabled in the browser to function.
  • Potential Performance Impact: While the library is lightweight, it still adds an additional dependency and processing overhead to the page.
  • Limited Browser Support: The library may not work perfectly in all older browsers, as it's a polyfill for a relatively new CSS feature.
  • Potential Conflicts with Other Libraries: The library may not play well with other JavaScript libraries or frameworks that also manipulate the DOM.

Code Examples

Here are a few examples of how to use the object-fit-images library:

  1. Basic Usage:
import objectFitImages from 'object-fit-images';

// Initialize the library
objectFitImages();
  1. Targeting Specific Elements:
import objectFitImages from 'object-fit-images';

// Initialize the library and target specific elements
objectFitImages('img.my-images');
  1. Customizing the Behavior:
import objectFitImages from 'object-fit-images';

// Initialize the library with custom options
objectFitImages('.my-images', {
  watchMQ: true, // Watch for media query changes
  fittype: 'cover', // Set the default object-fit type
  disableCrossDomain: true // Disable cross-domain image support
});
  1. Updating the Library:
import objectFitImages from 'object-fit-images';

// Initialize the library and update the elements later
const ofi = objectFitImages();
ofi.update();

Getting Started

To use the object-fit-images library, follow these steps:

  1. Install the library using npm or yarn:
npm install object-fit-images
  1. Import the library and initialize it in your JavaScript code:
import objectFitImages from 'object-fit-images';

// Initialize the library
objectFitImages();
  1. Optionally, you can target specific elements or customize the behavior of the library:
// Target specific elements
objectFitImages('img.my-images');

// Customize the behavior
objectFitImages('.my-images', {
  watchMQ: true,
  fittype: 'cover',
  disableCrossDomain: true
});
  1. If you need to update the library's behavior after the initial setup, you can call the update() method:
const ofi = objectFitImages();
ofi.update();

That's it! With these simple steps, you can start using the object-fit-images library to polyfill the object-fit and object-position CSS properties in your web application.

Competitor Comparisons

A responsive image polyfill for <picture>, srcset, sizes, and more

Pros of picturefill

  • Broader support for responsive images, including <picture> element and srcset attribute
  • More comprehensive solution for cross-browser responsive image loading
  • Actively maintained with regular updates and bug fixes

Cons of picturefill

  • Larger file size and potentially more complex implementation
  • Focuses on responsive images rather than specifically addressing object-fit issues
  • May introduce additional overhead for simpler use cases

Code comparison

picturefill:

<picture>
  <source srcset="large.jpg" media="(min-width: 800px)">
  <source srcset="medium.jpg" media="(min-width: 400px)">
  <img src="small.jpg" alt="A responsive image">
</picture>

object-fit-images:

<img src="image.jpg" style="object-fit: cover; width: 100%; height: 300px;">

Summary

picturefill is a more comprehensive solution for responsive images across browsers, supporting various techniques like <picture> and srcset. It's actively maintained but may be overkill for simpler use cases. object-fit-images, on the other hand, focuses specifically on polyfilling the object-fit CSS property, making it a lighter and more targeted solution for that particular need. The choice between the two depends on the specific requirements of your project and the level of responsive image support you need.

📱 Make videos playable inline on the iPhone (prevents automatic fullscreen)

Pros of iphone-inline-video

  • Allows for inline video playback on iOS devices, which is not natively supported.
  • Provides a fallback solution for browsers that don't support the playsinline attribute.
  • Offers a simple and lightweight implementation.

Cons of iphone-inline-video

  • Requires additional JavaScript to be included in the project.
  • May not work as seamlessly as native playsinline support.
  • Doesn't provide the same level of control and customization as object-fit-images.

Code Comparison

object-fit-images

objectFitImages();

iphone-inline-video

const iphoneInlineVideo = require('iphone-inline-video');
iphoneInlineVideo(document.querySelectorAll('video'));
17,454

High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration.

Pros of lazysizes

  • More comprehensive lazy loading solution, handling images, iframes, and scripts
  • Supports automatic size calculation for responsive images
  • Includes plugins for additional features like LQIP (Low Quality Image Placeholders)

Cons of lazysizes

  • Larger file size due to more features (11.9KB vs 1.9KB for object-fit-images)
  • May be overkill for projects that only need object-fit polyfill
  • Requires more configuration for basic usage compared to object-fit-images

Code Comparison

lazysizes:

<img data-src="image.jpg" class="lazyload" />
<script src="lazysizes.min.js" async></script>

object-fit-images:

<img src="image.jpg" style="object-fit: cover;" />
<script src="ofi.min.js"></script>
<script>objectFitImages();</script>

Summary

lazysizes is a more feature-rich solution for lazy loading and responsive images, while object-fit-images focuses specifically on providing a polyfill for the object-fit CSS property. lazysizes offers more functionality but comes with a larger file size and potentially more complex setup. object-fit-images is simpler and lighter but limited to its specific use case. Choose based on your project's requirements and performance considerations.

JavaScript, SCSS, Sass, Less, and Stylus helpers for rendering high-resolution image variants

Pros of retinajs

  • Automatic Retina Image Handling: retinajs automatically detects and serves high-resolution images for Retina displays, improving the visual quality of your website.
  • Lazy Loading: retinajs supports lazy loading, which can improve page load times by only loading images when they are needed.
  • Responsive Design: retinajs can be used in conjunction with responsive design techniques to provide the best image quality for different screen sizes.

Cons of retinajs

  • Limited Image Formats: retinajs only supports JPEG and PNG image formats, which may not be suitable for all use cases.
  • Dependency on JavaScript: retinajs requires JavaScript to be enabled in the user's browser, which may not be the case for all users.
  • Potential Performance Impact: the additional JavaScript code required by retinajs may have a slight impact on page load times, especially on slower devices.

Code Comparison

fregante/object-fit-images

<img src="image.jpg" class="object-fit-polyfill">
.object-fit-polyfill {
  object-fit: cover;
  font-family: 'object-fit: cover;';
}

strues/retinajs

<img src="image.jpg" class="retina">
retinajs('.retina');

LazyLoad is a lightweight, flexible script that speeds up your website by deferring the loading of your below-the-fold images, backgrounds, videos, iframes and scripts to when they will enter the viewport. Written in plain "vanilla" JavaScript, it leverages IntersectionObserver, supports responsive images and enables native lazy loading.

Pros of Vanilla Lazyload

  • Lightweight: Vanilla Lazyload is a lightweight library, weighing in at around 3KB gzipped, making it a great choice for performance-conscious projects.
  • Versatile: The library supports a wide range of image formats, including <img>, <picture>, <video>, <iframe>, and custom elements.
  • Customizable: Vanilla Lazyload offers a range of configuration options, allowing you to tailor the library to your specific needs.

Cons of Vanilla Lazyload

  • Limited Functionality: Compared to object-fit-images, Vanilla Lazyload does not provide any functionality for handling image scaling and positioning, which may be a requirement for some projects.
  • Dependency on Intersection Observer: Vanilla Lazyload relies on the Intersection Observer API, which may not be supported in older browsers, potentially requiring a polyfill.

Code Comparison

Vanilla Lazyload:

const lazyload = new LazyLoad({
  elements_selector: ".lazy",
  use_native: true
});

object-fit-images:

objectFitImages();

As you can see, the Vanilla Lazyload code requires more setup and configuration, while object-fit-images is a more straightforward, one-liner solution.

:camera: JavaScript is all like "You images done yet or what?"

Pros of imagesloaded

  • Broader functionality: Handles various image loading scenarios, not limited to object-fit
  • Event-driven approach: Provides callbacks for different stages of image loading
  • Works with multiple images: Can handle groups or collections of images

Cons of imagesloaded

  • Larger file size: More comprehensive functionality results in a bigger library
  • Less specific: Not tailored for object-fit issues, which may require additional code
  • More complex setup: Requires more configuration for basic use cases

Code Comparison

object-fit-images:

objectFitImages('img.object-fit');

imagesloaded:

imagesLoaded( elem, callback )
  .on( 'progress', function( instance, image ) {
    var result = image.isLoaded ? 'loaded' : 'broken';
    console.log( 'image is ' + result + ' for ' + image.img.src );
  });

Summary

object-fit-images is a lightweight, focused solution for object-fit polyfilling, while imagesloaded offers broader image loading management. The choice depends on specific project needs: object-fit-images for simple object-fit support, or imagesloaded for comprehensive image loading control.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

object-fit-images gzipped size build status npm CDNJS jsDelivr

🗻 Polyfill object-fit/object-position on <img>: IE9, IE10, IE11, Edge, Safari, ...

  • Fast and lightweight (demo)
  • No additional elements are created
  • Setup is done via CSS
  • Scaling is taken care by the browser (it uses background-size)
  • srcset support
  • src and srcset properties and attributes keep working: img.src = 'other-image.jpg'

Alternative solutions

Comparisonfregante
/object-fit-images🌟
constancecchen
/object-fit-polyfill
tonipinel
/object-fit-polyfill
BrowsersIEdge 9-14, Android<5, Safari<10<- Same"All browsers"
Tagsimgimage video pictureimg
cover/contain💚💚💚
fill💚💚💚
none💚💚💚
scale-down💚 using {watchMQ:true}💚💔
object-position💚💚💔
srcset support💚 Native or picturefill notes💚💔
Extra elements💚 No💔 Yes💔 Yes
Settings💚 via CSS💔 via HTML💔 via HTML

Usage

You will need 3 things

  1. one or more <img> elements with src or srcset

    <img class='your-favorite-image' src='image.jpg'>
    
  2. 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.

  3. the activation call before </body>, or on DOM ready

    objectFitImages();
    // if you use jQuery, the code is: $(function () { objectFitImages() });
    

    This 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:

    // pass a selector
    objectFitImages('img.some-image');
    
    // an array/NodeList
    var someImages = document.querySelectorAll('img.some-image');
    objectFitImages(someImages);
    
    // a single element
    var oneImage = document.querySelector('img.some-image');
    objectFitImages(oneImage);
    
    // or with jQuery
    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 resize

You don't need to re-apply it on resize, unless:

In one of those cases, use the watchMQ option:

objectFitImages('img.some-image', {watchMQ: true});
// or objectFitImages(null, {watchMQ: true}); // for the auto mode

Install

Pick your favorite:

<script src="dist/ofi.min.js"></script>
<!-- CDN is also available, but I suggest you concatenate JS files instead -->
<!-- Visit https://cdnjs.com/libraries/object-fit-images -->
npm install --save object-fit-images
var objectFitImages = require('object-fit-images');
import objectFitImages from 'object-fit-images';

API

objectFitImages(images, options)

Both parameters are optional.

parameter description
images Type: string, element, array, NodeList, null
Default: null

The images to fix. More info in the Usage section
options Type: object
Default: {}
Example: {watchMQ:true}

watchMQ Type: boolean
Default: false

This enables the automatic re-fix of the selected images when the window resizes. You only need it in some cases

License

MIT © Federico Brigante

NPM DownloadsLast 30 Days