使用纯css优雅配置移动端rem布局

780 阅读1分钟

原文 | 奇思站 (isme.top)

通常配置rem布局会使用js进行处理,比如750的设计稿会这样配置

function responseAdjust(width = 750) {
  var htmlDom = document.documentElement
  htmlDom.style.fontSize = htmlDom.clientWidth / width * 100 + "px"
}
responseAdjust()
window.onresize = function() {
  return responseAdjust()
}

如果需要配置响应式断点,如屏幕宽度大于600px或者小于300px时不必再响应式了,可以这样配置(相信我,这样的场景还是很多的,比如移动端的H5网站需要在PC端也能正常显示)

function responseAdjust(width = 750, minWidth = 300, maxWidth = 450) {
  var htmlDom = document.documentElement
  var clientWidth = htmlDom.clientWidth
  if(clientWidth > maxWidth) {
    clientWidth = maxWidth
  }
  if(clientWidth < minWidth) {
    clientWidth = minWidth
  }
  htmlDom.style.fontSize = clientWidth / width * 100 + "px"
}
responseAdjust()
window.onresize = function() {
  return responseAdjust()
}

虽然代码不多,但总觉得不是很优雅,这些事能否交给css去处理呢。其实是可以的,而且还很优雅

先上个最简单的

html {
  font-size: calc(100vw / 7.5);
}

关键在于calc和vw属性,calc代表计算,vw代表窗口的宽度的比例,即100vw表示100%的窗口宽度

再结合媒体查询做断点处理

html {
  font-size: calc(100vw / 7.5);
}

@media screen and (min-width: 600px) {
  html {
    font-size: calc(600px / 7.5);
  }
}

@media screen and (max-width: 300px) {
  html {
    font-size: calc(300px / 7.5);
  }
}

是不是瞬间觉得优雅了呢,效果跟js处理方式是一样的