缩放div以适应窗口,但保留宽高比 [英] Scale a div to fit in window but preserve aspect ratio
问题描述
如何缩放div以适合浏览器视图端口,但保留div的宽高比。如何使用CSS和/或JQuery?
How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?
谢谢!
推荐答案
这不需要javascript。您可以使用纯CSS。
You don't need javascript for this. You can use pure CSS.
相对于包含块宽度,解释padding-top百分比。将它与位置:绝对的子元素结合,您可以在保留其长宽比的框中添加任何东西。
A padding-top percentage is interpreted relative to the containing block width. Combine it with position: absolute on a child element, and you can put pretty much anything in a box that retains its aspect ratio.
HTML:
<div class="aspectwrapper">
<div class="content">
</div>
</div>
CSS:
.aspectwrapper {
display: inline-block; /* shrink to fit */
width: 100%; /* whatever width you like */
position: relative; /* so .content can use position: absolute */
}
.aspectwrapper::after {
padding-top: 56.25%; /* percentage of containing block _width_ */
display: block;
content: '';
}
.content {
position: absolute;
top: 0; bottom: 0; right: 0; left: 0; /* follow the parent's edges */
outline: thin dashed green; /* just so you can see the box */
}
display:inline-block
在 .aspectwrapper
框底部留下一点额外的空间,因此下面的另一个元素不会运行冲洗。使用 display:block
将会消除它。
The display: inline-block
leaves a little extra space below the bottom edge of the .aspectwrapper
box, so another element below it won't run flush against it. Using display: block
will get rid of it.
感谢这篇文章的提示!
另一种方法依赖于以下事实:当您只调整其宽度或高度时,浏览器会考虑图像的宽高比。 (我会让google生成一个16x9的透明图片用于演示,但实际上您会使用自己的静态图片。)
Another approach relies on the fact that browsers respect an image's aspect ratio when you resize only its width or height. (I'll let google generate a 16x9 transparent image for demonstration purposes, but in practice you would use your own static image.)
HTML:
<div class="aspectwrapper">
<img class="aspectspacer" src="http://chart.googleapis.com/chart?cht=p3&chs=160x90" />
<div class="content">
</div>
</div>
CSS:
.aspectwrapper {
width: 100%;
position: relative;
}
.aspectspacer {
width: 100%; /* let the enlarged image height push .aspectwrapper's bottom edge */
}
.content {
position: absolute;
top: 0; bottom: 0; right: 0; left: 0;
outline: thin dashed green;
}
这篇关于缩放div以适应窗口,但保留宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!