FLEX 网格布局及响应式处理
上一篇文章用Flex实现BorderLayout,这一章我们来实现常用的网格布局和响应式处理.
首先我们定义HTML结构,主Box为grid,每项为grid-cell,下面就是我们HTML代码结构.
<divclass="grid"><divclass="grid-cell">1</div><divclass="grid-cell">2</div></div>
grid为flex容器,grid-cell为flex项,我们加入CSS代码
.grid{display:flex;flex-wrap:wrap;justify-content:space-around;}.grid-cell{flex-grow:1;flex-shrink:1;padding:10px;}
了解过前两篇flex布局文章,代码没什么好解释的了,space-around是为了保证flex项之间的距离相等.grid-cell里设置为等比例的放大或缩小.
在这里,我们在.grid-cell里面加入一个demo盒子,这是为了更好的去控制grid-cell元素,不破坏flex布局的功能性,也就是各自负责各自的事情.为了效果好看,我加入了更多的网格模式.HTML结构,如下
<divclass="grid"><divclass="grid-cell"><divclass="demo">1</div></div><divclass="grid-cell"><divclass="demo">2</div></div></div><divclass="grid"><divclass="grid-cell"><divclass="demo">1</div></div><divclass="grid-cell"><divclass="demo">2</div></div><divclass="grid-cell"><divclass="demo">3</div></div></div><divclass="grid"><divclass="grid-cell"><divclass="demo">1</div></div><divclass="grid-cell"><divclass="demo">2</div></div><divclass="grid-cell"><divclass="demo">3</div></div><divclass="grid-cell"><divclass="demo">4</div></div></div>
CSS代码:
.grid{display:flex;flex-wrap:wrap;justify-content:space-around;}.grid-cell{flex-grow:1;flex-shrink:1;padding:10px;}.demo{background-color:#eeeeee;min-height:50px;text-align:center;width:100%;;}
demo里面设定高度和背景色,为了布局能够正确显示出来.
最终效果如下图:
网格布局,我们就实现了.现在不同以往只需要对电脑做好显示效果就可以了,如今社会,智能设备遍地都是.而人们使用智能设备的时间也远远大于PC,智能设备上显示也是重中之重,响应式布局也就出来了.
响应式布局用到的是media这个属性,所以处理起来也是很简单的.我们只需要加入下面的代码:
@media(max-width:768px){.grid-cell{flex-basis:100%;}}
就完成了上面网格布局的不同设备显示效果.我们这里是超过768像素的设备就正常显示,如果小于这个值,每个flex项就整行显示.看看效果:
本文属于吴统威的博客,微信公众号:bianchengderen的原创文章,转载时请注明出处及相应链接:http://www.wutongwei.com/front/infor_showone.tweb?id=150 ,欢迎大家传播与分享.
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。