前言
经过第一篇的知识点的学习以及flex青蛙的学习,我们下面在布局中找一些实用的案例进行分享学习吧。
布局实战
dom内容是不变的,作为公共部分。
<ul class="container"><li class="item">111111</li><li class="item">111111</li><li class="item">111111</li><li class="item">111111</li><li class="item">111111</li></ul>
左边浮动,项目之间固定间距
常规的向左浮动布局,每个内容固定宽度,向左间距固定
.container{display:flex;height:300px;border:1px solid red;flex-wrap:wrap;.item{border:1px solid #000;background:red;color:#fff;flex-basis:300px;margin-left:20px;height:100px;}}
向左浮动,均分中间等间距
常规的向左浮动布局,每个内容固定宽度,中间等分剩余间距
.container{display:flex;height:300px;border:1px solid red;flex-wrap:wrap;justify-content:space-between;.item{border:1px solid #000;background:red;color:#fff;flex-basis:300px;height:100px;}}
水平垂直居中布局
直接利用弹性盒本身的特性即可。
<div class="demo"><span>sdfwefer f</span></div>.demo{display:flex;border:1px solid red;height:50px;justify-content:center;align-items:center;}
等高容器布局
无论其他容器的高度是多少,其他的项目扩充到最高元素的高度。
代码地址:https://codepen.io/robinson90/pen/oNNrVXJ
ul{display:flex;li{flex:1;border:1px solid red;word-break:break-all;display:flex;align-items:center;// justify-content:center;}}
特别说明:重要的是flex:1本身就可以设置实现等高的效果,如果想要更详细的内容居中,可以内容再设置display:flex,并设置垂直居中以及水平居中即可。(当然如果不是直接内容,可以设置li的子元素的对其方式)
中间固定宽度,两边等分宽度
.container{display:flex;align-items:center;.left{flex:1;}.center{width:300px;}.right{flex:1;}}
中间变宽 ,两边固定宽度
左边内容宽度不确定,右边占据剩下的全部.如果你希望无论两者的高度占据多少,都能实现垂直居中的效果,容器样式增加align-items:center即可
.container{display:flex;align-items:center;.left{width:100px;//other width is also ok}.right{flex:1;}}
固定最小高度,固定底部预留空间
.container{display:flex;min-height:100vh;flex-direction:column;.body{flex:1;}.footer{height:200px;background:red;}}
