水平垂直居中方案

水平居中

内联元素

.center-text {
	text-align: center;
}

块级元素

.center-box {
	margin: 0 auto;
}

多块级元素
利用inline-block
如果一行中有两个或两个以上的块级元素,通过设置块级元素的显示类型为inline-block和父容器的text-align属性从而使多块级元素水平居中。

<div class="container">
    <div class="inline-block">
    </div>
    <div class="inline-block">
    </div>
    <div class="inline-block">
    </div>
</div>

.container {
	text-align: center;
}
.inline-block {
	display: inline-block;
}

利用flex

.flex-center {
	display: flex;
	justify-content: center;
}

垂直居中

单行内联元素

	height: 120px;
	line-height: 120px;

多行内联元素
利用表布局
利用表布局的vertical-align: middle可以实现子元素的垂直居中。

.center-table {
	display: table;
}
.v-cell {
	display: table-cell;
	vertical-align: middle;
}

利用flex布局

.center-flex {
	display: flex;
	flex-direction: column;
	justify-content: center;
}

固定高度的块级元素

.parent {
	position: relative;
}
.child {
	position: absolute;
	top: 50%;
	height: 100px;
	margin-top: -50px;
}

未知高度的块级元素

.parent {
	position: relative;
}
.child {
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}

水平垂直居中

已知宽度&绝对定位&margin负边距

<div class="box">
	<div class="content">
	</div>
</div>

.box {
	position: relative;
	width: 100px;
	height: 100px;
	background-color: red;
}
.content {
	position: absolute;
	width: 50px;
	height: 50px;
	padding: 10px;
	background-color: blue;
	left: 50%;
	top: 50%;
	margin: -35px 0 0 -35px;
}

已知宽度&绝对定位&margin : auto

<div class="box">
	<div class="content">
	</div>
</div>

.box {
	position: relative;
	width: 100px;
	height: 100px;
	background-color: red;
}
.content {
	position: absolute;
	width: 50px;
	height: 50px;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	margin: auto;
	background-color: blue;
}

未知宽度&绝对定位&transform

<div class="box">
	<div class="content">
	</div>
</div>

.box {
	position: relative;
	width: 100px;
	height: 100px;
	background-color: red;
}
.content {
	position: absolute;
	width: 50px;
	height: 50px;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	background-color: blue;
}

flex布局

<div class="box">
	<div class="content">
	</div>
</div> 

.box {
	display: flex;
	width: 100px;
	height: 100px;
	justify-content: center;
	align-item: center;
	background-color: red;
}
.content {
	width: 50px;
	height: 50px;
	background-color: blue;
}

屏幕上水平垂直居中
常规的登录及注册页面用得到,要保证好的兼容性,还需要用到表布局。
table-cell布局

.outer {
	display: table;
	position: abslute;
	width: 100%;
	height: 100%;
}
.middle {
	display: table-cell;
	vertical-align: middle;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值