<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
<style>
*{
margin: 0;
padding: 0;
}
/*根元素設(shè)置font-size*/
html {
font-size: 100px;
}
body {
font-size: 16px;
}
.box {
border: 1px solid gray;
width: 200px;
height: 200px;
font-size: 16px;
}
.inner {
border: 1px solid gray;
margin: 5px;
font-size: 2em;
/*字體會相對于父元素box的16px的2倍翔忽,2em是32px*/
height: 2em;
/* 當(dāng)em用于設(shè)置元素非字體屬性時,如果當(dāng)前對象顯示的設(shè)置了字體大小喊递,那么em參考的是自身的字體大小梭依。輸出是64px*/
}
.box2 {
border: 1px solid gray;
width: 200px;
height: 200px;
}
.inner2 {
border: 1px solid gray;
margin: 5px;
font-size: 1rem;
/*相對根節(jié)點字體大小节芥,輸出結(jié)果是100px*/
height: 1rem;
/*相對根節(jié)點字體大小吱瘩,輸出結(jié)果是100px*/
}
header {
width: 3.75rem;
height: 0.5rem;
font-size: 0.32rem;
background-color: black;
color: white;
font-weight: 600;
line-height: 0.5rem;
text-align: center;
}
</style>
</head>
<body>
<header>hello H5 耻台!</header>
<div class="box">
hello
<div class="inner">hello</div>
</div>
<div class="box2">
hello
<div class="inner2">hello</div>
</div>
</body>
<script type="text/javascript">
/*
em: 相對單位诚欠,相對父元素fontSize碳竟,比如父元素字體16px草丧, 1em=16px;
當(dāng)em用于設(shè)置元素非字體屬性時莹桅,如果當(dāng)前對象顯示的設(shè)置了字體大小昌执,那么em參考的是自身的字體大小。
rem:參考根節(jié)點字體大小的相對單位诈泼,html標(biāo)簽字體大小16px懂拾,1rem = 16px;
*/
// 獲取當(dāng)前視口寬度
var clientWidth = document.documentElement.clientWidth || document.body.offsetWidth;
// 獲取根元素html
var html = document.documentElement;
//獲取當(dāng)前視口寬度和標(biāo)準(zhǔn)寬度比例 * 標(biāo)準(zhǔn)rem單位得到html的font-size這里設(shè)置的行內(nèi)樣式權(quán)重最大
html.style.fontSize = clientWidth / 375 * 100 + "px";
// 監(jiān)聽window的onresize屏幕的尺寸變化
// 如果我們改變?yōu)闄M屏?xí)r,html的font-size發(fā)生變化
window.onresize = function () {
var clientWidth = document.documentElement.clientWidth || document.body.offsetWidth;
//獲取當(dāng)前視口寬度和標(biāo)準(zhǔn)寬度比例 * 標(biāo)準(zhǔn)rem單位
document.documentElement.style.fontSize = clientWidth / 375 * 100 + "px";
};
</script>
</html>