Flex 横向布局 · 换行 · 对齐

视频教程

Flex 横向布局

通过 display:flex; flex-direction:row; 可以声明 flex 横向布局 ( 基于主轴布局 )。

Flex 横向布局换行

默认情况下内部元素超过外层元素宽度时不会自动换行。

通过 flex-wrap:nowrap; 可以实现横向布局时,当内部元素超过外部横向宽度时缩小元素不换行的布局目标。

通过 flex-wrap:wrap; 可以实现横向布局时,当内部元素超过外部横向宽度时自动换行的布局目标。

flex-wrap 属性

nowrap	默认值,不换行
wrap	换行
wrap-reverse 换行并将元素倒序
inherit	从父元素继承该属性

示例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div class="flexBox">
	<div class="item">项目1</div>
	<div class="item" style="width:500px; margin:0 15px;">项目2</div>
	<div class="item">项目3</div>
</div>
<style type="text/css">
.flexBox{
	display:flex; 
	flex-direction:row; 
	flex-wrap:nowrap; 
	width:900px; 
	background:#F8F8F8; 
	padding:10px; 
	box-sizing:border-box;
	justify-content:space-between;
}
.item{
	background-color:aquamarine; 
	width:280px; height:100px; 
	text-align:center; 
	line-height:100px;
}
</style>
</body>
</html>

主轴对齐

通过外部元素的 justify-content 样式属性可以控制内部元素的横向( 主轴 )对齐方式, justify-content 属性值的意义 :

flex-start	默认值。从行首起始位置开始排列
flex-end	从行尾位置开始排列
center	居中排列 
space-between	均匀排列每个元素,首个元素放置于起点,末尾元素放置于终点
space-evenly	均匀排列每个元素,每个元素之间的间隔相等
space-around	均匀排列每个元素,每个元素周围分配相同的空间
initial	设置该属性为它的默认值
inherit	从父元素继承该属性

交叉轴对齐

通过 align-items 属性可以控制内部元素的竖向( 交叉轴 )对齐方式,align-items 属性值的意义 :

stretch 默认值。元素被拉伸以适应容器
center 元素位于容器的中心
flex-start 元素位于容器的开头
flex-end 元素位于容器的结尾
baseline 元素位于容器的基线上
inherit	从父元素继承该属性

示例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div class="flexBox">
	<div class="item">项目1</div>
	<div class="item" style="height:80px; line-height:80px;">项目2</div>
	<div class="item">项目3</div>
</div>
<style type="text/css">
.flexBox{
	display:flex; 
	flex-direction:row; 
	flex-wrap:nowrap; 
	width:900px; 
	background:#F8F8F8; 
	padding:10px; 
	box-sizing:border-box;
	justify-content:space-between;
	align-items:center;
}
.item{
	background-color:aquamarine; 
	width:280px; height:100px; 
	text-align:center; 
	line-height:100px;
}
</style>
</body>
</html>