基础知识:http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool)
等分:flex:1
<div class="main">
<div class="item">1</div>
<div class="item">1</div>
<div class="item">1</div>
</div>
<!--css样式 -->
.main {
display: flex;
}
.item {
flex: 1;
}
居中:两个属性justify-content: center; align-items: center;
<div class="main">
<div class="item"></div>
</div>
.main {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
}
.item {
width: 100px;
height: 100px;
}
左定宽右自适应:左元素定宽,右宽度100%
<div class="main">
<div class="item left">左边</div>
<div class="item right">1</div>
</div>
.main {
display: flex;
min-height: 100vh;
}
.item {
height: 100%;
}
.left {
width: 300px;
}
.right {
width: 100%;
}
三栏布局-左右定宽中间自适应:中间flex:1;左右宽度写死
<div class="main">
<div class="item left">左</div>
<div class="item center">中</div>
<div class="item right">右</div>
</div>
.main {
display: flex;
min-height: 100vh;
}
.item {
height: 100%;
}
.left {
width: 100px;
}
.center {
flex: 1;
}
.right {
width: 100px;
}
九宫格布局:flex:1;
<div class="container">
<div class="row">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
<div class="row">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
<div class="row">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
</div>
.container {
display: flex;
min-height: 100vh;
}
.row {
flex: 1;
display: flex;
}
.left {
flex: 1;
}
.middle {
flex: 1;
}
.right {
flex: 1;
}
阶梯布局:item本身属性align-self子项本身的属性,可以单独设置对齐方式
<div class="main">
<div class="item item1">1</div>
<div class="item item2">1</div>
<div class="item item3">1</div>
</div>
.main {
display: flex;
min-height: 100vh;
}
.item {
border: 1px solid saddlebrown;
box-sizing: border-box;
flex: 1;
}
.item1 {
align-self: flex-start;
}
.item2 {
align-self: center;
}
.item3 {
align-self: flex-end;
}
圣杯布局:上下固定高度,中间左右固定高度。自适应为flex:1;固定高度用flex-basic:100px;
<div class="container">
<div class="header">Header</div>
<div class="content">
<div class="content-left">Left</div>
<div class="content-middle">Center</div>
<div class="content-right">Right</div>
</div>
<div class="footer">Footer</div>
</div>
.container{
display: flex;
min-height: 100vh;
flex-direction: column;
justify-content: space-between;
}
.header{
flex: 0 0 100px;
background-color: royalblue;
}
.content{
display: flex;
flex: 1;
}
.content-left{
flex: 0 0 100px;
background-color: saddlebrown;
}
.content-right{
flex: 0 0 100px;
background-color: darkgreen;
}
.content-middle{
flex: 1;
background-color:blanchedalmond;
}
.footer{
flex: 0 0 100px;
background-color: red;
}
原文地址:https://juejin.im/post/5e43b8d3e51d45270e2116d0