CSS keep aspect ratio, but fill parent div
Basically, I have an image that I want to hide in a circle.
<div class="thumbnail-mask"> <img class="thumbnail-pic" src="/image.jpeg"> </div> CSS (I use LESS) is pretty simple:
.thumbnail-mask { width: @circleSize; height: @circleSize; border-radius: @circleSize/2; -webkit-border-radius: @circleSize/2; -moz-border-radius: @circleSize/2; overflow: hidden; } I figured out how to center the image inside the parent both vertically and horizontally
.thumbnail-pic { text-align: center; position: relative; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); // width: 100%; // height: auto; height:auto; width: 100%; } But now the problem is height and width.
If I try height:100%; width:100%; height:100%; width:100%; , aspect ratio will be changed.
If height> width, then I want width: 100%; height: auto; width: 100%; height: auto; . If width> height, I want height: 100%; width: auto height: 100%; width: auto . Thus, the circle is completely filled. But this is not possible. I tried to set min-width:100%; min-height:100% min-width:100%; min-height:100% , but without setting the height or width, the image is too large.
One solution is to use jquery to set the width and height of the image based on the aspect ratio
$(document).ready(function () { $("img").each(function () { // Calculate aspect ratio and store it in HTML data- attribute var aspectRatio = $(this).width() / $(this).height(); $(this).data("aspect-ratio", aspectRatio); // Conditional statement if (aspectRatio > 1) { // Image is landscape $(this).css({ height: "100%" }); } else if (aspectRatio < 1) { // Image is portrait $(this).css({ width: "100%" }); } }); }); Obviously this is not as elegant as pure css methods, but is likely to be more reliable