Flex布局专题

  • Flex布局,就是 flexible box(弹性布局)

  • 注意事项: 当对容器使用flex布局以后
    子元素的 float/clear/vertical-align属性将失效

  • flex项目(flex item): 就是容器的子元素

  • 容器默认存在两根'轴'

    • 水平主轴(main axis)

    • 垂直交叉轴(cross axis)

  • 以下6个属性设置在容器上(即,属于容器的属性)

- flex-direction(主轴方向)

- flex-wrap(折行)

- flex-flow

- justify-content(主轴方向上,项目如何排列)

- align-items(交叉轴方向上,项目如何排列)

- align-content(折行以后,项目之间的间距)

flex-direction 有4个值

  • flex-direction: row/row-reverse/column/column-reverse

flex-wrap 折行显示

- nowrap: 默认值,不换行
- wrap:换行
- wrap-reverse:反向换行

flex-flow 是 flex-direction 和 flex-wrap的简写形式

  • 容器里面,放小盒子测试效果
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.container {
				width: 600px;
				height: 600px;
				background: red;
				display: flex;
				/* flex-wrap: wrap; */
				flex-flow: row wrap-reverse;
				
			}
			.container div {
				width: 150px;
				height: 100px;
				border: 1px solid black;
				box-sizing: border-box;
			}
		</style>
	</head>
	
	<body>
		<div class="container">
			<div>111</div>
			<div>222</div>
			<div>333</div>
			<div>444</div>
			<div>555</div>
			<div>666</div>
			<div>777</div>
			<div>888</div>
		</div>
		
	</body>
</html>

  • justify-content: 规定项目在主轴方向的对齐方式
- flex-start(默认值):左对齐
- flex-end:右对齐
- center:居中
- space-between:两端对齐,项目之间的间隔都相等
- space-around:每个项目两侧的间隔相等(所以,该间隔比"项目与边框的间隔大一倍")
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			.container {
				width: 600px;
				height: 400px;
				background: skyblue;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				
			}
			.container div {
				width: 100px;
				height: 80px;
				background: yellow;
				box-sizing: border-box;
				border: 2px solid purple;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<div>111</div>
			<div>222</div>
			<div>333</div>
			<div>444</div>
		</div>
	</body>
</html>