Flexbox 弹性布局完全指南
Flexbox 提供了一种更有效的方式来布局、对齐和分配容器中项目的空间。
容器属性
display
.container {
display: flex;
/* 或 */
display: inline-flex;
}
flex-direction
.container {
flex-direction: row; /* 默认,水平从左到右 */
flex-direction: row-reverse; /* 水平从右到左 */
flex-direction: column; /* 垂直从上到下 */
flex-direction: column-reverse; /* 垂直从下到上 */
}
flex-wrap
.container {
flex-wrap: nowrap; /* 默认,不换行 */
flex-wrap: wrap; /* 换行 */
flex-wrap: wrap-reverse; /* 反向换行 */
}
justify-content
.container {
justify-content: flex-start; /* 默认 */
justify-content: flex-end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
}
align-items
.container {
align-items: stretch; /* 默认 */
align-items: flex-start;
align-items: flex-end;
align-items: center;
align-items: baseline;
}
项目属性
flex-grow
.item {
flex-grow: 0; /* 默认 */
flex-grow: 1; /* 占据剩余空间 */
}
flex-shrink
.item {
flex-shrink: 1; /* 默认,允许收缩 */
flex-shrink: 0; /* 不收缩 */
}
flex-basis
.item {
flex-basis: auto; /* 默认 */
flex-basis: 200px;
flex-basis: 50%;
}
flex 简写
.item {
flex: 0 1 auto; /* 默认 */
flex: 1; /* flex: 1 1 0% */
flex: auto; /* flex: 1 1 auto */
flex: none; /* flex: 0 0 auto */
}
align-self
.item {
align-self: auto; /* 继承容器 */
align-self: flex-start;
align-self: flex-end;
align-self: center;
align-self: baseline;
align-self: stretch;
}
实用布局示例
水平垂直居中
.container {
display: flex;
justify-content: center;
align-items: center;
}
等分列
.container {
display: flex;
}
.item {
flex: 1;
}
圣杯布局
.layout {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header, .footer {
flex: none;
}
.main {
display: flex;
flex: 1;
}
.content {
flex: 1;
}
.sidebar {
flex: 0 0 200px;
}
粘性页脚
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.content {
flex: 1;
}
CSS
返回首页