To rotate an image within its parent div while keeping it contained and avoiding overlap, you need to adjust the image’s rotation without causing it to exceed the boundaries of the parent element. The problem you’re facing with libraries like jQuery Rotate is that they usually rotate the image around its center, which can cause parts of the image to overflow out of its container.
One simple approach is to use CSS to rotate the image using the transform property while setting the transform-origin to ensure the rotation occurs within the bounds of the parent div. You can control the rotation angle dynamically with JavaScript.
Example:
<div class="parent" style="width: 300px; height: 300px; overflow: hidden; position: relative;">
<img id="image" src="your-image.jpg" style="width: 100%; height: 100%; object-fit: contain;">
</div>
<button id="button">Rotate</button>
var angle = 0;
$('#button').on('click', function() {
angle += 90;
$('#image').css({
'transform': 'rotate(' + angle + 'deg)',
'transform-origin': 'center center'
});
});
Key Points: The transform-origin is set to ‘center center’, ensuring the image rotates around its center point.
The object-fit: contain ensures the image stays within the bounds of its parent while scaling.
This method works well if you want a smooth rotation without worrying about the image overflowing or clipping.