【问题标题】:CSS preserve aspect ratio but fill parent divCSS保留纵横比但填充父div
【发布时间】:2014-07-25 05:45:22
【问题描述】:

基本上,我有一个图像,我想用一个圆圈来遮盖。

<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,但是为容器的 deminions 设置了一个特定的宽度和高度吗?我认为这就是我实现相同目标的方式

标签: html css less


【解决方案1】:

Fiddle For Example

一种解决方法是使用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 方法来说并不那么优雅,但最终可能会更可靠

【讨论】:

  • 这基本上就是我现在要做的。但它确实减慢了浏览器的速度。尤其是当我有一堆这些并且在渲染时有一堆反应性回调。
  • 好吧,我明白你在说什么另一种方法是稍微调整html结构并将图像作为背景图像然后使用封面。 See this fiddle
  • 我之前的评论中有一个小提琴链接
【解决方案2】:

.thumbnail-mask 中的display:inline-block; 应该将&lt;img&gt; 包裹在其中

【讨论】: