CSS preserve aspect ratio but fill parent div

谁说胖子不能爱 提交于 2019-12-23 15:13:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!