垂直居中几种常见的实现方式总结

垂直居中几种常见的实现方式总结

1.使用flex实现 垂直居中。
①、使用flex的justify-content和align-items属性

.parent {
		    height: 500px;
		    background-color: #ccc;
			display: flex;
			align-items: center;
			justify-content: center;
		}
.son{
			width: 100px;
			height: 100px;
			background-color: red;
		}

②、flex使用margin平分间距

.parent{
			height: 500px;
			display: flex;
			background-color: #0000FF;
}
.son{
			height: 100px;
			width: 100px;
			background-color: red;
			margin: auto;
}

2.使用position定位实现垂直居中。
①设置left、right、bottom、top为0,使用margin调整间距

.parent{
			height: 500px;
			position: relative;
			background-color: #0000FF;
			}
.son{
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			top: 0;
			height: 100px;
			width: 100px;
			background-color: red;
			margin: auto;
			}

②知道子元素宽高的情况使用margin负值调整。

.parent{
			height: 300px;
			position: relative;
			background-color: #0000FF;
			}
.son{
				position: absolute;
				left: 50%;
				top: 50%;
				height: 100px;
				width: 100px;
				background-color: red;
				margin-left: -50px;
				margin-top: -50px;
			}

③不知道子元素宽高的情况使用transform属性。

.parent{
			height: 300px;
			position: relative;
			background-color: #0000FF;
			}
.son{
				position: absolute;
				left: 50%;
				top: 50%;
				background-color: red;
				transform: translate(-50%, -50%); 
			}

还有一种方式是使用display=table和table-cell实现,这种方式没有兼容问题,上面的flex和transform都存在兼容性问题。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值