「4种方案」搞定CSS水平垂直居中

2,011 阅读2分钟

方案一:position绝对定位+margin负值

  • 适用:子元素有宽高尺寸
  • 方法:父元素相对定位,子元素绝对定位,left和top定位到父元素50%,再用margin向左和向上移动子元素尺寸的一半。
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		position: relative;
}
.content{
		background: #FFB90F;
		width: 200px;
		height:200px;
		position: absolute;
		left: 50%;
		top:50%;
		margin:-100px 0 0 -100px;
}

效果:

方案一

方案二:position绝对定位+transform调整位置

  • 适用:子元素未知宽高(当然知道也可以啦!)
  • 方法:此方法与方案一是一个道理,将margin换为transform:translate(-50%,-50%)。
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		position: relative;
	}
.content{
		background: #FFB90F;
		/*width: 200px;*/
		/*height:200px;*/
		position: absolute;
		left: 50%;
		top:50%;
		transform: translate(-50%,-50%);
}

效果:

方案二.png

方案三:position绝对定位+margin:auto

  • 适用:子元素有宽高尺寸
  • 方法:父元素相对定位,子元素绝对定位,left、right、top、bottom设置为0,再用margin:auto。
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		position: relative;
	}
.content{
		background: #FFB90F;
		width: 200px;
		height:200px;
		position: absolute;
		left: 0;
		right:0;
		top:0;
		bottom:0;
		margin:auto;
}

效果:与方案一相同。

方案四:flex弹性盒

  • 适用:子元素未知宽高(当然知道也可以啦!)
  • 方法:父元素设置为弹性盒,justify-content和align-items都设置为center居中。
.wrapper{
		background: #1890ff;
		height: 400px;
		width:400px;
		display: flex;
		justify-content: center;/*主轴方向居中*/
		align-items:center;/*侧轴方向居中*/
	}
.content{
		background: #FFB90F;
		/*width: 200px;*/
		/*height:200px;*/
}

效果:与方案二相同。