引用js,自动算字体大小,响应式布局
<script>
var iScale = 1; iScale = iScale / window.devicePixelRatio; document.write('<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=' + iScale + ',minimum-scale=' + iScale + ',maximum-scale=' + iScale + '">');/* 动态设置字体大小*/
function htmlFontSizeChange() { var iWidth = document.documentElement.clientWidth; document.getElementsByTagName('html')[0].style.fontSize = iWidth / 16 + 'px'; console.log("1rem = " + iWidth / 16); } htmlFontSizeChange(); $(window).resize(function() { htmlFontSizeChange(); }); </script><style>
body{
font-size:1rem; /*(16px)/(iWidth/16) (iWidth设计图宽)*/
}
</style>
示例
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8"> <title></title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> var iScale = 1; iScale = iScale / window.devicePixelRatio; document.write('<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=' + iScale + ',minimum-scale=' + iScale + ',maximum-scale=' + iScale + '">');/* 动态设置字体大小*/
function htmlFontSizeChange() { var iWidth = document.documentElement.clientWidth; document.getElementsByTagName('html')[0].style.fontSize = iWidth / 16 + 'px'; console.log("1rem = " + iWidth / 16); } htmlFontSizeChange(); $(window).resize(function() { htmlFontSizeChange(); }); </script> <style> span { font-size: 0.21333333rem; /*设计图大小为1200,16/(1200/16)*/ /*font-size: 16px;*/ } div { width: 0.4rem; /*30/(1200/16)*/ /*width: 30px;*/ background: red; height: 0.4rem; } </style> </head><body>
<span>设计图宽度为1200</span> <div></div> </body></html>
直接使用css设置rem
html{
font-size:62.5%; /* 10÷16=62.5% */
}
body{
font-size:12px;
font-size:1.2rem ; /* 12÷10=1.2 */
}
媒体查询
@media only screen and (min-width: 481px){
html {
font-size: 94%!important;/* 15.04÷16=94% */
}
}
@media only screen and (min-width: 561px){
html {
font-size: 109%!important; /* 17.44÷16=109% */
}
}
@media only screen and (min-width: 641px){
html {
font-size: 125%!important;/* 20÷16=125% */
}
}
引用来自