CSS元素居中

本文详细介绍了如何使用CSS实现元素的水平居中、垂直居中以及水平垂直居中,涵盖了flex布局、text-align、margin、position+margin/transform等多种方法,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CSS元素居中

水平居中

flex布局

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

text-align

对inline inline-block inline-table inline-flex都有效,用在父元素

.parent {
	text-align: center;
}

对块元素,可以转为行内块,然后父元素text-align

将内部转为行内块然后外部text-align,这种方法也适用于内部多个块的情况

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

margin

定宽:左右margin

.child {
	width: 100px; /* 确保内部块是定宽 */
	margin: 0 auto;
}

内容宽:table+margin

子元素设置为块级表格,再将其水平居中

display: table在表现上类似block,但宽度为内容宽

.child {
	display: table; /* 宽度为内容宽,根据内容自动调整宽高 */
	margin: 0 auto;
}

内容宽:flex+margin

.parent {
	display: flex;
}
.child {
	margin: 0 auto;
}

定宽:子绝父相+margin

子绝父相,子元素设置左右距离均为0,然后加上margin auto,注意一定要给子元素设定宽度否则会自动撑满

.parent {
	position: relative;
}
.child {
	position: absolute;
	width: 100px; /* 一定要有,否则自动计算的margin值会为0,而该子盒子宽度会撑满整行 */
	left: 0;
	right: 0;
	margin: 0 auto;
}

position+(margin/transform)

主要指通过定位(子绝父相 / 子元素relative)将子元素向右移动父元素的一半,然后再向左移动自身的一半(translateX或负margin)

使用translateX无需子元素定宽,而使用负margin子元素必须定宽

translateX:子绝父相,向右移动子元素,距离为父容器的一半;再向左移动子元素的一半

.parent {
	position: relative;
}
.child {
	position: absolute;
	left: 50%; /* 向右移动父容器的一半 */
	transform: translateX(-50%); /* 再向左移动自身的一半 */
}

负margin:子元素relative+负margin

.child {
	width: 500px;
	position: relative;
	left: 50%; /* 向右移动parent的一半 */
	margin-left: -250px; /* 向左移动自身的一半 */
}

垂直居中

flex布局

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

或者使用align-items

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

table+vertical-align

.parent {
	display: table;
}
.child {
	display: table-cell;
	vertical-align: middle;
}

vertical-align只对inline和table-cell有效

单行inline:height=line-height

position+(margin/transform)

水平垂直居中

flex

.parent {
	display: flex;
	justify-conent: center;
	align-items: center;
}

或者直接

.parent {
	display: flex;
}
.child {
	margin: auto;
}

table

.parent {
	display: table;
	text-align: center;
}
.child {
	display: table-cell;
	vertical-align: middle;
}

position+(margin/transform)

margin

同前margin部分,如果要使用margin+子绝父相则必须要子元素定宽高,垂直方向父元素也要定高

.parent {
	position: relative;
	height: 500px; /* 必须定高,否则子元素绝对定位撑不起父元素 */
}
.child {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	margin: auto;
	height: 100px;
	width: 100px;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值