CSS之水平、垂直及水平垂直居中

本文总结了布局中实现元素水平居中、垂直居中及水平垂直居中的常用方法

一、水平居中

1)文本 / 行内元素 / 行内块级元素

#parent { text-align: center; }

2)单个块级元素

ele {
	width: 100px;   // 必须定宽
	margin: 0 auto;
}

3)多个块级元素

#parent {
		text-align: center;
}
.son {
		display: inline-block;
}

4)子元素实现居中,使用绝对定位实现 (子绝父相)

#parent {
		position: relative;
		width: 200px;
}
#son {
	position: absolute;
	left: 50%;   // 父元素宽度的一半
	width: 100px;
	transform: translateX(-50%);  // 向左拉回子元素自身宽度的一半
}

5)任意个元素(flex)

#parent {
		display: flex;
		justify-content: center;
}

二、垂直居中

1)单行文本 / 行内元素 / 行内块级元素

#parent {
		height: 150px;
		line-height: 150px;
}

2)多行文本(文本用一个标签包裹起来)

#parent {
		height: 200px;
		line-height: 200px;
}
.son {
	display: inline-block;
	vertical-align: middle;
	line-height: 20px;
}

3)图片

#parent {
		height: 150px;
		line-height: 150px;
		font-size:0;
}
img {
	vertical-align: middle;
}

4)单个块级元素

#parent {
		position: relative;
		height: 200px;
}
#son {
		position: absolute;
		top: 50%;
		height: 100px;
		transform: translateY(-50%);
}

或
原理: 当元素的 top、bottom为0时,该元素的 margin-top/bottom设置为auto的话会自动分配剩余空间
#son {
	position: absolute;
	top: 0;
	bottom: 0;
	height: 100px;
	margin: auto 0;   
}

5)任意个元素(flex)

#parent {
		display: flex;
		align-items: center;
}		

三、水平垂直居中

1)text-align、line-height及vertical-align三者结合

#parent {
		width: 500px;
		height: 500px;
		line-height: 500px;
		text-align: center;
}
#son {
		display: inline-block;
		width: 200px;
		height: 200px;
		line-height: 20px;
		vertical-align:middle;
}

2)table-cell

#parent {
		 display: table-cell;
	     width: 600px;
	     height: 400px;
	     vertical-align: middle;
	     text-align: center;
	     background-color: skyblue;
}
#son {
         display: inline-block;
		 width: 200px;
	     height: 300px;
	     background-color: slateblue;
}

3)绝对定位

#parent {
		position: relative;
}
#son {
		position: absolute;
		top: 50%;
		left: 50%;
		width: 200px;
		height: 200px;
		transform: translate(-50%, -50%);
}

4)绝对居中
原理:当元素的 top、bottom、left、right同时为0时,该元素的 margin-top/bottom/left/right设置为 auto 的话会自动平分剩余空间

#parent {
	position:relative;
}
#son {
	position: absolute;
	left:0;
	right:0;
	top:0;
	bottom:0;
	width:200px;
	height:200px;
	margin: auto;
}

5)flex

#parent {
		display:flex;
		justify-content:center;
		align-items:center;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值