Flex布局详解
简介
Flex(Flexible Box)布局模型是一种高效且便于布局、对齐内容的一维布局模型,可用于解决复杂的布局挑战,特别适用于应用程序组件和小型布局。
基础概念
- 容器(Container): 使用
display: flex
或display: inline-flex
的元素被称为Flex容器。 - 项目(Item): 容器内的子元素自动成为Flex项目。
容器属性
display
使用 display: flex
或 display: inline-flex
可以定义一个Flex容器。
.container {display: flex; /* or inline-flex */
}
flex-direction
这个属性定义了主轴,决定了项目的排列方向。
.container {flex-direction: row | row-reverse | column | column-reverse;
}
justify-content
定义了项目在主轴上的对齐方式。
.container {justify-content: flex-start | flex-end | center | space-between | space-around;
}
align-items
定义项目在交叉轴上如何对齐。
.container {align-items: flex-start | flex-end | center | baseline | stretch;
}
flex-wrap
定义项目是否换行。
.container {flex-wrap: nowrap | wrap | wrap-reverse;
}
align-content
多行的对齐方式。
.container {align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
项目属性
order
定义项目的排列顺序。
.item {order: <integer>;
}
flex-grow
定义项目的放大比例。
.item {flex-grow: <number>;
}
flex-shrink
定义了项目的缩小比例。
.item {flex-shrink: <number>;
}
flex-basis
定义了在分配多余空间之前,项目占据的主轴空间。
.item {flex-basis: <length> | auto;
}
align-self
允许单个项目与其他项目不同的对齐方式。
.item {align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
实例
HTML:
<div class="container"><div class="item">1</div><div class="item">2</div><div class="item">3</div>
</div>
CSS:
.container {display: flex;justify-content: space-between;align-items: center;
}.item {width: 100px;height: 100px;background-color: LightSkyBlue;text-align: center;line-height: 100px;
}
总结
Flex布局非常强大,适用于各种复杂的布局需求。掌握了以上属性,你应该可以自如地使用Flex进行页面布局了。
希望这篇博客能帮助你更好地理解和使用Flex布局!有其他问题,随时提出。