Appearance
html
<!--
1rem 在 1920px 宽度的屏幕下是 100px,在大于 1920px 宽度的屏幕下会大于 100px,
在小于 1920px 宽度的屏幕下会小于 100px。所以如果设计稿宽度是 1920px,而你在屏幕
宽度不足 1920px 的设备上开发时会出现写 1rem,但实际比 100px 更小,可以将分辨率
宽度改为 1920px 进行统一。
-->
<div style="width: 1rem; height: 1rem;"></div>
<script>
const adapter = () => {
const html = document.documentElement
const width = html.clientWidth
// 1920 是设计稿的宽度
const rootValue = width / 1920 * 100
html.style.fontSize = `${ rootValue }px`
}
adapter()
// 缩放时也开启适配
window.addEventListener('resize', adapter)
</script>js
const adapter = () => {
const html = document.documentElement
const width = html.clientWidth
// 如果使用了 tailwind,它的默认 rootValue 是 16px。
// 1rem => 16px => class="w-10" => width: 160px
// 如果直接 width / 1920 * 100,假设宽度为 1900px
// class="w-10" => width: (100 / 16) * 160
// 应该通过 16 / 1920 = rootValue / width 计算出 rootValue
const rootValue = 16 * width / 1920
html.style.fontSize = `${ rootValue }px`
}
adapter()