CSS保留宽高比,但填充父div [英] CSS preserve aspect ratio but fill parent div
问题描述
基本上,我有一个图像,我想用一个圆圈。
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>
CSS(我使用LESS)非常简单:
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.
如果我尝试 height:100%;
If I try height:100%; width:100%;
the aspect ratio is changed.
如果height> width,那么我想要 width:100 %; height:auto;
。如果width> height,我想要 height:100%; width:auto
。这样,圆完全填满。但这似乎是不可能的。我尝试设置 min-width:100%;
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.
推荐答案
一个解决方案是使用jquery基于长宽比设置图像宽度和高度
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%"
});
}
});
});
显然,这不像纯CSS方法那么优雅,但是最终可能会更可靠
Obviously this isn't quite as elegant to pure css methods, but will probably end up being more reliable
这篇关于CSS保留宽高比,但填充父div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!