Scale And Position Image In Img Tag - jQuery img2bg.js

File Size: 6.36 KB
Views Total: 895
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Scale And Position Image In Img Tag - jQuery img2bg.js

The img2bg.js (image to background) is a tiny (less than 1kb) and easy-to-use jQuery plugin that makes an image behave like a background image.

The plugin enables you to scale and position an image inside its <img /> tag just like you use the CSS background properties to fill and center a background image inside a container element.

Useful in cases where the images should have a fixed size without distortion.

How to use it:

1. Load the minified version of the img2bg.js plugin after jQuery library.

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

2. Set a fixed size for your image.

<img class="example" src="1.jpg" />
img {
  width: 400px;
  height: 300px;
}

3. Call the function and determine how to scale the image. The image can be left to its natural size, stretched, or constrained to fit the available space:

  • cover (Default): Scales the image as large as possible without stretching the image.
  • contain: Scales the image as large as possible without cropping or stretching the image.
  • auto: Scales the image in the corresponding direction such that its intrinsic proportions are maintained.
$(".example").img2bg({
  imageSize: "cover"
});

$(".example").img2bg({
  imageSize: "contain"
});

$(".example").img2bg({
  imageSize: "auto"
});

4. Determine how to position the image. The image can be left to its natural size, stretched, or constrained to fit the available space:

  • center
  • top
  • left
  • right
  • bottom
$(".example").img2bg({
  imagePosition: "center center"
});

5. Determine whether to repeat the image just like a background.

  • repeat
  • repeat-x
  • repeat-y
  • no-repeat
$(".example").img2bg({
  imageRepeat: "no-repeat"
});

6. Append a CSS class to the wrapper element so that you can customize the styles of the image in the CSS.

$(".example").img2bg({
  divSelector: "myContainer"
});
div.myContainer {
  border: 3px solid #fff;
  border-radius: 3px;
}

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