当前位置:   article > 正文

flex布局中子元素水平垂直居中的方法_flex子元素垂直居中

flex子元素垂直居中

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

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

		<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号