前端工程师最害怕的写得最多的界面就是APP界面,但是不同的手机屏幕宽度不一样,宽度变了样式就会混乱,有什么解决办法呢?下面介绍几个自适应样式。
- rem布局之媒体查询
html{
font-size: 38px;
}
@media only screen and (min-width: 320px) {
html {
font-size: 42.666px !important;
}
}
@media only screen and (min-width: 360px) {
html {
font-size: 48px !important;
}
}
@media only screen and (min-width: 375px) {
html {
font-size: 50px !important;
}
}
@media only screen and (min-width: 414px) {
html {
font-size: 55.2px !important;
}
}
@media only screen and (min-width: 480px) {
html {
font-size: 64px !important;
}
}
@media only screen and (min-width: 560px) {
html {
font-size: 74.666px !important;
}
}
@media only screen and (min-width: 640px) {
html {
font-size: 85.333px !important;
}
}
@media only screen and (min-width: 720px) {
html {
font-size: 96px !important;
}
}
@media only screen and (min-width: 750px) {
html {
font-size: 100px !important;
}
}
@media only screen and (min-width: 800px) {
html {
font-size: 106.666px !important;
}
}
@media only screen and (min-width: 960px) {
html {
font-size: 128px !important;
}
}
这是最早使用的方法,缺点是需要知道不同的手机的宽度,然后根据比例设置不同的font-size的值。
2 .使用vw作为CSS像素单位
在sass预编译处理器中:
$vm_base:640; //设计图的宽度
@function vw($px) {
@return ($px / $vm_base) * 100vw;
}
.box{
width: vw(300); //只需要写设计图的宽高即可
height: vw(300);
border: 1px solid red ;
}
个人觉得这种方法比较好用,只需要写一套样式即可,不需要知道各种手机的宽度,vw会根据比例在手机中显示。sass会自动帮你把px转换成vw,不需要自己去计算。
下面是sass编译成.css文件后的css代码
.box {
width: 46.875vw;
height: 46.875vw;
border: 1px solid red; }
3.利用SASS函数功能实现px转rem
html{
font-size: 100px;
}
$baseFontSize:100;//基数
@function px2rem($px){
@return $px / $baseFontSize * 1rem;
}
//调用
.box{
width: px2rem(600);
height: px2rem(400);;
background-color: lawngreen;
}
这种方法跟第2种差不多,都是利用sass将px转换成不同的单位,但是仍然需要匹配多种不同的样式来适应不同的手机。
青菜萝卜各有所爱,就看你们自己喜欢哪种方式啦!