CSS常用水平垂直居中的几种方法


HTML代码如下:

<div class="outer">
    <div class="inner"></div>
  </div>

css代码如下:

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
}

1. 子元素相对于父元素绝对定位,子元素top,left设置50%,子元素margin-top和margin-left减去各自宽高的一半

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
	position: relative;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
	position: absolute;
	left: 50%;
	top: 50%;
	margin-left: -100px;
	margin-top: -100px;
}

2. 子元素相对父元素绝对定位,子元素top,left值为50%,transform:translate(-50%,-50%)

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
	position: relative;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}

3. 子元素相对于父元素绝对定位,子元素上下左右全为0,然后设置子元素margin: auto

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
	position: relative;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	margin: auto;
}

4. 子元素相对定位,子元素top,left值为50%,transform: translate(-50%, -50%);

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
	position: relative;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}

5. 父元素设置弹性盒子,display:flex; justify-content:center ;align-items:center;

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
	display: flex;
	justify-content: center;
	align-items: center;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
}

6. 父元素设置display:table-cell; vertical-align:middle; 子元素设置margin:auto。

.outer {
	width: 600px;
	height: 600px;
	border: 1px solid #f00;
	display: table-cell;
	vertical-align: middle;
}

.inner {
	width: 200px;
	height: 200px;
	background-color: aqua;
	margin: auto;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端~初学者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值