根据浏览器的高度和宽度保持长宽比和字体大小? [英] Maintain aspect ratio and font size based on browser height and width?

查看:720
本文介绍了根据浏览器的高度和宽度保持长宽比和字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码附加到 window.onresize = resize; 。在加载时读取 baseWidth baseHeight 作为计算的基础。 main 变量只是通过将其设置到主html节点来定义。在块元素上设置字体,以使其中的所有基于 em 的元素以实物大小调整。当浏览器的宽度或高度更改时,将重新计算比率。请参阅演示,了解我使用JS实现的目标,但希望找到一个纯CSS解决方案: http:// codepen .io / anon / pen / nLauF

The code below is attached to window.onresize = resize;. The baseWidth and baseHeight are read on load as a basis for the calculations. The main variable is defined just by setting it to the main html node. The font is set on a block element to cause all of the em based elements within it to resize in kind. When the width or height of the browser is changed then the ratio is recalculated. Please see demo to understand what I achieve with JS but would like to find a pure CSS solution: http://codepen.io/anon/pen/nLauF

我一直在探索CSS3中的选项,例如 calc 。也可以随意建议对以下JS的任何改进。

I have been exploring options in CSS3 such as calc. Feel free to also suggest any improvements to the JS below also.

             function resize() {
                var height = 0,
                    width = 0;

                if(window.innerWidth <= window.innerHeight) {
                    size = window.innerWidth / baseWidth;
                    height = baseHeight * size;
                    width = window.innerWidth;

                } else {
                    size = window.innerHeight / baseHeight;
                    height = window.innerHeight;
                    width = baseWidth * size;
                }

                if(baseWidth * size > window.innerWidth) {
                    size = window.innerWidth / baseWidth;
                    height = baseHeight * size;
                    width = window.innerWidth;
                }

                main.style.height = height + "px";
                main.style.width = width + "px";
                main.style.fontSize = size * 16 + "px";
            }

谢谢!

推荐答案

我写了这个代码包括字体大小计算与 vmin units

I wrote this code including font-size calculation with vmin units :

DEMO

DEMO

CSS:

CSS :

main {
    width: 80vmin;
    height: 60vmin;
    background-color: #000;
    position: absolute;
    top:0; bottom:0;
    left:0; right:0;
    margin:auto;
}
h1 {
    color: #fff;
    font-size: 30px; /* general fallback */
    font-size: 5vm; /* IE9 fallback */
    font-size: 5vmin;
}

对于浏览器支持,可以检查 canIuse

For browser support, you can check canIuse

这篇关于根据浏览器的高度和宽度保持长宽比和字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆