Skip to main content

适配rem

index.html

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8"/>
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Document</title>
<script>
const clientWidth = document.documentElement.clientWidth
const clientHeight = document.documentElement.clientHeight
window.pageWidth = clientWidth / clientHeight > 16 / 9 ? clientHeight * (16 / 9) : clientWidth
const pageHeight = pageWidth / (16 / 9)
const string = `
<style>html{
font-size: ${pageWidth / 100}px
}</style>`
document.write(string)
</script>
</head>
<body>
<div id="root"></div>
<script>
// root.style.width = pageWidth + 'px'
root.style.height = pageHeight + 'px'
root.style.marginTop = (clientHeight - pageHeight) / 2 + 'px'
</script>
</body>
</html>

help.scss

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-size: 16px;
}

$designWidth: 2420;

@function px($n){
@return $n / $designWidth * 100rem;
}

app.scss

@import "helper";

.child {
width: px2rem(400);
height: px2rem(200);
}

参考

使用SCSS完成动态rem适配的自动计算