做移动端页面时,如果只按照设计稿抄尺寸,会遇到大屏幕手机能完整展示设计稿,换到小屏幕手机,设计稿下半部分会被切掉的情况,此时可以使用弹性布局进行页面的适配
整体思路
页面整体使用flex弹性布局,根据设计稿的元素排列,将设计稿切分成若干块,元素基于切分后的盒子进行定位
参考资料(阮一峰Flex 布局教程)://www.ruanyifeng.com/blog/2015/0…
页面布局
首先定义页面大小和区块划分,例如设计稿的元素是上中下布局,就将页面切分成上中下三栏的布局
<!-- 页面整体 -->
<div class="main">
<!-- 上部分盒子 -->
<div class="one"> </div>
<!-- 中间盒子 -->
<div class="two"></div>
<!-- 底部盒子 -->
<div class="three"> </div>
</div>
接下来就是设置页面为flex弹性布局,将页面设置为 display: flex;,页面是上中下布局,通过修改flex-direction属性为column达到垂直排列
引用阮一峰的教程,flex-direction有以下几种排列方向
完整的布局代码如下,此时就能获得一个垂直弹性布局的容器了
.main {
display: flex;
display: -webkit-flex;
flex-direction: column;
width: 100vw;
height: 100vh;
}
设置完容器属性,就要对内部的盒子进行大小控制了,利用flex-grow属性,将子盒子划分成需要的大小
例如:父盒子300px,设置flex-grow:1,每个子盒子大小就是300/3,为三等分
加上flex-grow的布局的代码如下
.main {
display: flex;
display: -webkit-flex;
flex-direction: column;
width: 100vw;
height: 100vh;
}
.one {
flex-grow:1;
background-color: aquamarine;
}
.two {
flex-grow:2;
background-color: firebrick;
}
.three {
flex-grow:1;
background-color: coral;
}
此时页面已经完成了划分,可以在设计稿上用辅助线进行相应的切割。并且对盒子进行定位。
- 划分出来的每个子盒子为绝对定位
- 把元素设置成相对定位 当屏幕分辨率改变的时候,子盒子会相应的伸缩,元素依然保持当前位置不变。这样就能达到根据屏幕不同尺寸缩放的效果了
完整代码
<!-- 页面布局 -->
<div class="main">
<!-- 上部分盒子 -->
<div class="one">
one
<div class="inner_one">inner_one</div>
</div>
<!-- 中间盒子 -->
<div class="two">
two
<div class="inner_two">inner_two</div>
</div>
<!-- 底部盒子 -->
<div class="three">
three
<div class="inner_three">inner_three</div>
</div>
</div>
/* css */
.main {
display: flex;
display: -webkit-flex;
flex-direction: column;
width: 100vw;
height: 100vh;
}
.one {
flex-grow:1;
position: relative;
background-color: aquamarine;
}
.inner_one {
width: 100px;
height: 50px;
background-color: floralwhite;
position: absolute;
top: 50px;
left: 10px;
}
.two {
flex-grow:2;
position: relative;
background-color: firebrick;
}
.inner_two {
width: 100px;
height: 50px;
background-color: floralwhite;
position: absolute;
bottom: 10px;
right: 50px;
}
.three {
flex-grow:1;
position: relative;
background-color: coral;
}
.inner_three {
width: 100px;
height: 50px;
background-color: floralwhite;
position: absolute;
bottom: 10px;
left: 10px;
}