CSS保持宽高比并填充父级div

4

基本上,我有一张图片想要用圆形进行遮罩。

<div class="thumbnail-mask">
  <img class="thumbnail-pic" src="/image.jpeg">
</div>

CSS(我使用LESS)非常简单:
.thumbnail-mask {
  width: @circleSize;
  height: @circleSize;
  border-radius: @circleSize/2;
  -webkit-border-radius: @circleSize/2;
  -moz-border-radius: @circleSize/2;
  overflow: hidden;
}

我已经找到了如何在父元素中垂直水平居中图片的方法。
.thumbnail-pic {
  text-align: center;
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);

  // width: 100%;
  // height: auto;
  height:auto;
  width: 100%;
}

现在的问题是高度和宽度。

如果我尝试使用height:100%; width:100%;,则会改变纵横比。

如果高度>宽度,则希望使用width: 100%; height: auto;。如果宽度>高度,则希望使用height: 100%; width: auto。这样,圆形图像将完全填充。但似乎不可能实现。我尝试设置min-width:100%; min-height:100%,但是如果不设置高度或宽度,则图像太大了。


你是否尝试过使用max-height和max-width,同时将容器的宽度和高度设置为特定值?我认为这就是我实现相同目标的方法。 - Brett Weber
2个回答

1

例如Fiddle

一种解决方案是使用jquery根据宽高比设置图像的宽度和高度。

$(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方法那样优雅,但很可能会更可靠。

这基本上是我现在正在进行的工作。但它真的会拖慢浏览器。特别是当我有一堆这些东西并且它们渲染时有一堆反应式回调函数。 - Chet
好的,我明白你的意思了。另一种方法是稍微调整一下HTML结构,将图像作为背景图片,然后使用cover属性。请参见此fiddle - joegandy
我之前的评论中有一个fiddle链接 - joegandy

0

display:inline-block;.thumbnail-mask 中应该包裹其中的 <img>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接