一、基础网格布局
最简单的网格布局,就是平均分布。在容器里面平均分配空间,需要设置项目的自动缩放。
HTML结构:
<div class="box Grid">
<div class="Grid-cell">1/2</div>
<div class="Grid-cell">1/2</div>
</div>
<div class="box Grid">
<div class="Grid-cell">1/3</div>
<div class="Grid-cell">1/3</div>
<div class="Grid-cell">1/3</div>
</div>
<div class="box Grid">
<div class="Grid-cell">1/4</div>
<div class="Grid-cell">1/4</div>
<div class="Grid-cell">1/4</div>
<div class="Grid-cell">1/4</div>
</div>
CSS样式:
.box .Grid-cell {
border: 1px solid #ccc;
height: 32px;
line-height: 32px;
}
.Grid {
display: flex;
}
.Grid .Grid-cell {
flex: 1; // 将等分主轴的剩余空间
}
二、百分比布局
某个网格的宽度为固定的百分比,其余网格平均分配剩余的空间。
HTML结构:
<div class="box Grid">
<div class="Grid-cell u-lof1">1/2</div>
<div class="Grid-cell">auto</div>
<div class="Grid-cell">auto</div>
</div>
<div class="box Grid">
<div class="Grid-cell">auto</div>
<div class="Grid-cell u-lof2">1/3</div>
</div>
<div class="box Grid">
<div class="Grid-cell u-lof3">1/4</div>
<div class="Grid-cell">auto</div>
<div class="Grid-cell u-lof2">auto</div>
</div>
CSS代码:
.Grid {
display: flex;
}
.Grid .Grid-cell {
flex: 1; // 将等分主轴的剩余空间
}
.Grid .u-lof1 {
flex: 0 0 50%;
}
.Grid .u-lof2 {
flex: 0 0 33.33%
}
.Grid .u-lof3 {
flex: 0 0 25%
}
三、圣杯布局
HTML结构:
<div class="HolyGrail">
<div class="header">header</div>
<div class="HolyGrail-body">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
<div class="footer">footer</div>
</div>
CSS代码:
.HolyGrail {
display: flex;
flex-direction: column;
}
.HolyGrail div {
border: 1px solid #ddd;
line-height: 32px;
}
.HolyGrail .header, .HolyGrail .footer {
flex: 0 0 100%;
}
.HolyGrail-body{
display: flex;
flex: 1;
min-height: 100px;
}
.HolyGrail-body .left, .HolyGrail-body .center, .HolyGrail-body .right {
flex: 1;
}
四、悬挂式布局
有时需要在主栏的左侧或右侧,需要添加一个图片栏。
HTML结构:
<div class="Media">
<img src="" alt="这里是图片">
<p class="Media-body">这里是很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的文字</p>
</div>
CSS代码:
.Media {
display: flex;
align-items: flex-start;
}
.Media-body {
flex: 1;
margin: 0 0 0 8px;
padding: 0;
}
五、固定的底栏
有时,页面需要一个固定在底部的footer。
HTML结构:
<div class="Site">
<div>header</div>
<div class="Site-content">main content</div>
<div>footer</div>
</div>
CSS代码:
.Site {
display: flex;
min-height: 400px;
flex-direction: column;
}
.Site div {
border: 1px solid #ddd;
}
.Site-content {
flex: 1;
}
六、流式布局
每行的项目数固定,超过固定数目时,会自动分行。
HTML结构:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
CSS代码:
.parent {
width: 200px;
height: 150px;
background-color: black;
display: inline-flex;
flex-flow: row wrap;
align-content: flex-start;
}
.child {
box-sizing: border-box;
background-color: white;
flex: 0 0 25%;
height: 50px;
border: 1px solid red;
}