问题
Basically, I have an image that I want to mask with a circle.
<div class="thumbnail-mask">
<img class="thumbnail-pic" src="/image.jpeg">
</div>
The CSS (I'm using 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've figured out how to center the image within 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 issue is height and width.
If I try height:100%; width:100%;
the aspect ratio is changed.
If height > width, then I want width: 100%; height: auto;
. If width > height, I want height: 100%; width: auto
. This way, the circle is entirely filled out. But this doesn't seem to be possible. I've tried setting min-width:100%; min-height:100%
but then without setting the height or the width, the image is way too big.
回答1:
Fiddle For Example
One solution is to use jquery to set image width and height 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 isn't quite as elegant to pure css methods, but will probably end up being more reliable
回答2:
display:inline-block;
in .thumbnail-mask
should wrap the <img>
inside of it
来源:https://stackoverflow.com/questions/24944354/css-preserve-aspect-ratio-but-fill-parent-div