负责任地改变div尺寸保持高宽比

负责任地改变div尺寸保持高宽比

当我给一个图像百分之一的宽度或高度,它会增长/缩小,保持它的纵横比,但如果我想要与另一个元素相同的效果,它有可能把宽度和高度用百分比绑在一起吗?



江户川乱折腾
浏览 435回答 3
3回答

UYOU

您可以使用纯CSS完成此操作;不需要JavaScript。这利用了(有点违背直觉的)事实padding-top百分比相对于包含块的百分比宽度..下面是一个例子:.wrapper {&nbsp; width: 50%;&nbsp; /* whatever width you want */&nbsp; display: inline-block;&nbsp; position: relative;}.wrapper:after {&nbsp; padding-top: 56.25%;&nbsp; /* 16:9 ratio */&nbsp; display: block;&nbsp; content: '';}.main {&nbsp; position: absolute;&nbsp; top: 0;&nbsp; bottom: 0;&nbsp; right: 0;&nbsp; left: 0;&nbsp; /* fill parent */&nbsp; background-color: deepskyblue;&nbsp; /* let's see it! */&nbsp; color: white;}<div class="wrapper">&nbsp; <div class="main">&nbsp; &nbsp; This is your div with the specified aspect ratio.&nbsp; </div></div>

慕娘9325324

<style>#aspectRatio{ &nbsp;&nbsp;position:fixed; &nbsp;&nbsp;left:0px; &nbsp;&nbsp;top:0px; &nbsp;&nbsp;width:60vw; &nbsp;&nbsp;height:40vw; &nbsp;&nbsp;border:1px&nbsp;solid; &nbsp;&nbsp;font-size:10vw;}</style><body><div&nbsp;id="aspectRatio">Aspect&nbsp;Ratio?</div></body>这里要注意的关键是vw=视口宽度vh=视口高度
打开App,查看更多内容
随时随地看视频慕课网APP