Maintain aspect ratio and font size based on browser height and width?

江枫思渺然 提交于 2019-12-06 12:39:27

I wrote this code including font-size calculation with 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;
}

For browser support, you can check canIuse

JRulle

I adapted a piece of CSS i wrote for a different project to solve your problem: JSFiddle DEMO I achieved the aspect ration of 4-3 by using a .75 multiplier (i.e. the width of main is 50% and the height should be 75% of that so the padding-top is 37.5%). You can see how these are adjustable to lock in your ratio.

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

This would require you to modify your HTML like so:

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

reference 1 -- this reference is my original solution used to keep images locked into an aspect ratio responsively

reference 2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!