最近在开发一个微信小程序的项目,用flex布局那叫一个爽,这里记录一下心得。
这里不再累诉flex的基础知识了(可以到以下链接学习,网上有很多)
http://www.runoob.com/w3cnote/flex-grammar.html
https://www.jianshu.com/p/494230cd4a72
1、九宫格
<style type="text/css">
*{margin: 0;padding: 0;list-style: none;}
ul{
display: flex;
flex-wrap: wrap;//超出换行
}
li{
width: 33%;
height: 60px;
display: flex;
justify-content: center;//子元素水平居中
align-items: center;//子元素垂直居中
}
div{
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
}
</style>
<body>
<ul>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
</ul>
</body>
2、头部&底部固定,中间区域滚动
这种布局非常常见,还可以衍化成上部或者底部固定,中间主体区域滚动。用手机录的屏,效果还好。代码如下:
<style type="text/css">
*{margin: 0;padding: 0;}
html,body{
width: 100%;
height: 100%;
}
.container{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
#head{
font-weight: bolder;
font-size: 25px;
height: 50px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: center;
align-items: center;
}
#content{
flex: 1;
padding: 20px;
overflow-y: scroll;
}
#btn{
font-weight: bolder;
font-size: 20px;
width: 100%;
background-color: firebrick;
padding: 10px 0;
color: #fff;
display: flex;
justify-content: center;
}
</style>
<body>
<div class="container">
<div id="head">xxx标题</div>
<div id="content">
<p>内容内容内容内容内容内容内容内容容内容内容内容内</p>
<p>内容内容内容内容内容内容内容内容容内容内容内容内</p>
<p>内容内容内容内容内容内容内容内容容内容内容内容内</p>
<p>内容内容内容内容内容内容内容内容容内容内容内容内</p>
</div>
<div id="btn">编辑</div>
</div>
</body>
说明:flex:1会让容器自动撑满剩余区域;justify-content: center会让子元素水平居中; align-items: center会让子元素垂直居中,不管是文字还是标签都有效。
文字垂直居中很多人会使用line-hight来设置,如果不知道容器高度时,有多行文字时line-hight的值该是多少呢?
3、瀑布流
这里用jquery随机生成的伪数据。在实际项目中如果是图片需要通过图片的宽高和容器的宽,按照比例计算出图片在容器需要显示的高度,这样就避免图片失真。如果是普通的文字信息就让它自己撑开容器的高度。
<style type="text/css">
*{margin: 0;padding: 0;}
html,body{
width: 100%;
height: 100%;
}
.container{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
#head{
font-weight: bolder;
font-size: 25px;
height: 50px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: center;
align-items: center;
}
#content{
flex: 1;
overflow-y: scroll;
display: flex;
}
ul{
padding: 5px;
list-style: none;
width: 50%;
}
ul li{
box-shadow: 0px 1px 1px 0px rgba(0,0,0,0.5);
margin-top: 10px;
background-color: #eee;
}
</style>
<body>
<div class="container">
<div id="head">瀑布流</div>
<div id="content">
<ul></ul>
<ul></ul>
</div>
</div>
</body>
暂时就先写到这三种,后面有时间在往后添加!
希望对您有所微薄的帮助!
向上的路并不拥挤,到多数人选择了安逸!--it疯子也