Resize And Center An Image To Fill Its Container - jQuery centerImage

Resize And Center An Image To Fill Its Container - jQuery centerImage
File Size: 3.09 KB
Views Total: 306
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

How To Resize And Center An Image To Fill Its Container?

In modern web development, developers are able to resize (stretch or crop) an image to fill its parent container using the object-fit CSS property:

  • object-fit: fill: The entire image will completely fill the container. If the image's aspect ratio does not match the aspect ratio of its container, then the image will be stretched to fit.
  • object-fit: cover: The image is resized to maintain its aspect ratio while filling the container's entire content box. If the image's aspect ratio does not match the aspect ratio of its container, then the image will be clipped to fit.
<img src="1.jpg" alt="Image Alt" class="fill" />
<img src="2.jpg" alt="Image Alt" class="cover" />
.fill {
  object-fit: fill;
}

.cover {
  object-fit: cover;
}

Resize And Center An Image To Fill Its Container Using jQuery

The object-fit CSS property currently supports almost all modern browsers such as Chrome, Firefox, Safari, etc. It is not, however, works properly in Internet Explorer.

centerImage is a cross-browser, JavaScript (jQuery) solution to proportionally resize (stretch or crop depending on the image and container size) and center an image to fill its parent container with no distortion. Ultra-light and dead simple to use. Have fun with it.

How to use it:

1. Download the plugin and load the JavaScript file centerImage.js after loading the latest jQuery library.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/centerImage.js"></script>

2. Add the CSS class center-img-container to the image container and specify the height & width of an image. That's it.

<div class="box center-img-container">
  <img src="1.jpg" width="400" height="300">
</div>
.box { 
  width: 600px; 
  height: 450px; 
  border: 2px solid #222;
}

This awesome jQuery plugin is developed by PankajRasgania. For more Advanced Usages, please check the demo page or visit the official website.