flex布局中如何让子元素水平垂直居中

思路:

  1. 先让子元素在主轴上居中对齐:justify-content: center;
  2. 再让子元素在侧轴上居中对齐:align-items: center;(单行) 或者 align-content: center;(多行)

注意:不要忘了给父元素添加display:flex;,这是开启 flex 布局的钥匙

举例说明:
单行子元素实现水平垂直居中:

		<div>
			<span>1</span>
			<span>2</span>
			<span>3</span>
		</div>
		<style type="text/css">
			div{
				display: flex;	
				width: 800px;
				height: 400px;
				background-color: orange;
				justify-content: center;
				align-items: center;
			}
			div span{
				width: 150px;
				height: 100px;
				background: skyblue;
				margin: 0 10px;
			}
		</style>

运行结果:
在这里插入图片描述
多行子元素实现水平垂直居中:

		<div>
			<span>1</span>
			<span>2</span>
			<span>3</span>
			<span>4</span>
			<span>5</span>
			<span>6</span>
		</div>
		<style type="text/css">
			div{
				display: flex;	
				width: 800px;
				height: 400px;
				background-color: orange;
				flex-wrap: wrap;
				justify-content: center;
				align-content: center;
			}
			div span{
				width: 150px;
				height: 100px;
				background: skyblue;
				margin: 10px;
			}
		</style>

运行结果:
在这里插入图片描述

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐