html – CSS保留纵横比但填充父div

html – CSS保留纵横比但填充父div,第1张

概述基本上,我有一个我想用圆圈掩盖的图像. <div class="thumbnail-mask"> <img class="thumbnail-pic" src="/image.jpeg"></div> CSS(我使用LESS)非常简单: .thumbnail-mask { width: @circleSize; height: @circleSize; border-radius 基本上,我有一个我想用圆圈掩盖的图像.

<div >  <img  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%;}

但现在问题是身高和宽度.

如果我尝试身高:100%;宽度:100%;宽高比改变了.

如果高度>宽度,然后我要宽度:100%;身高:自动;如果宽度>身高,我想身高:100%;宽度:自动.这样,圆圈就完全填满了.但这似乎不可能.我试过设置最小宽度:100%; min-height:100%但是没有设置高度或宽度,图像太大了.

解决方法 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 – CSS保留纵横比但填充父div全部内容,希望文章能够帮你解决html – CSS保留纵横比但填充父div所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1055425.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存