css实现水平垂直居中的方法

1、使用position定位实现垂直居中
<1>知道子元素宽高的情况使用margin负值调整
①使用绝对定位left:50%与margin-left取宽度值一半的复数形式设置水平居中。
②使用绝对定位top:50%与margin-top取高度值一半的复数形式设置垂直居中

/* 父元素相对定位,使子元素相对父元素绝对定位 */
.parent{
		position: relative;
		width: 600px;
		height: 600px;
		background-color: skyblue;
}
.child{
		position: absolute;
		width: 200px;
		height: 200px;
		background-color: #b1ebab;	
		left: 50%;
		top: 50%;
		/*用于目标元素宽高已确定 */
		margin-left: -100px;
		margin-top: -100px;		
}

<2>不知道子元素宽高的情况使用transform属性

.parent{
		position: relative;
		width: 600px;
		height: 600px;
		background-color: skyblue;
}
.child{
		position: absolute;
		width: 200px;
		height: 200px;		
		background-color: #b1ebab;
		left: 50%;
		top: 50%;
		/* 用于目标元素宽高不确定 */
		transform: translate(-50%,-50%); 
}

<3>设置left、right、bottom、top为0,使用margin: auto;调整间距

.parent {
				height: 500px;
				position: relative;
				background-color: #90d5ff;
			}

.child {
				position: absolute;
				left: 0;
				right: 0;
				bottom: 0;
				top: 0;
				height: 100px;
				width: 100px;
				background-color: #B1EBAB;
				margin: auto;
			}

2、 Flex布局 居中
<1>使用flex的justify-content和align-items属性

.parent {
				height: 500px;
				display: flex;
				/*元素垂直居中 */
				align-items: center;
				/* 元素水平居中 */
				justify-content: center;
				background-color: #87CEEB;
			}

.child {
				width: 200px;
				height: 200px;
				background-color: #B1EBAB;				
			}

<2>使用margin: auto;调整

.parent {
				height: 500px;
				display: flex;				
				background-color: #87CEEB;
			}

.child {
				width: 200px;
				height: 200px;
				background-color: #B1EBAB;				
				margin: auto; 
			}

3、借助table-cell,display: table-cell; vertical-align: middle;

.parent {
				display: table-cell;
				vertical-align: middle;
				text-align: center;
				width: 500px;
				height: 500px;
				background-color: #87CEEB;
			}

.child {
				display: inline-block;
				width: 50%;
				height: 50%;
				background: orange;
			}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值