【问题标题】:Maintain aspect ratio and font size based on browser height and width?根据浏览器的高度和宽度保持纵横比和字体大小?
【发布时间】:2014-09-16 01:01:21
【问题描述】:

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

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

             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";
            }

谢谢!

【问题讨论】:

标签: css aspect-ratio


【解决方案1】:

我用vmin units写了这段代码,包括字体大小计算:

DEMO

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

【讨论】:

【解决方案2】:

我改编了我为另一个项目编写的一段 CSS 来解决您的问题:JSFiddle DEMO 我通过使用 0.75 乘数实现了 4-3 的纵横比(即 main 的宽度为 50%,高度应为 75%,因此 padding-top 为 37.5%)。您可以查看如何调整这些以锁定您的比率。

.main {
  width: 50% !important;
  height: 0;
  display: block;
  overflow: hidden;
  line-height: 0;
  position: relative;
  padding: 37.5% 0 0 0;
  background-color: #000;
  margin: 0 auto;
}
.main-inner {
  position: absolute;
  display: block;
  margin: auto;
  top: 10px;
  left: 10px;
  bottom: 10px;
  right: 10px;
}
.main-inner-relative {
    position: relative;
    padding: 10px;
}
p { 
  color: white; 
  padding: 0;
  margin: 0;
}

这需要你像这样修改你的 HTML:

<div class="main">
    <div class="main-inner">
        <div class="main-inner-relative">
            <p>hello</p>
        </div>
    </div>
</div>

reference 1 -- 这个参考是我的原始解决方案,用于将图像锁定在响应式宽高比中

reference 2

【讨论】:

猜你喜欢
  • 2014-07-01
  • 2018-04-29
  • 1970-01-01
  • 2015-01-21
  • 2021-06-23
  • 2015-05-22
  • 2014-12-13
  • 1970-01-01
相关资源
最近更新 更多