White Meta
登录Admin
语言
中文EN
Theme: ...

© 2026 White Meta

回到顶部

返回文章列表

CSS查缺补漏2(居中)

水平居种方式

  1. 水平 margin auto

margin: 0 auto;

原理:当 margin 值为 auto 时,元素会尝试占据尽可能大的空间。比如,margin-left 会让 div 尽量靠最右侧。

margin: 0 auto; 相当于垂直margin: 0的同时,让 margin-left: auto 和 margin-right: auto,所以把盒子挤在水平居中位置。

  1. flex 布局

display: flex;
justify-content: center;

垂直居中

  1. 绝对定位

.parent {
	position: relative;
}
.child {
	width: 100px;
	height: 100px;
	position: absolute;
	left: 50%;
	top: 50%;
	margin-left: -50px;
	margin-top: -50px;
	/*
	或者:
	1. transform: translateX(-50px) translateY(-50px);
	2. left: calc(50% - 50px); right: calc(50% - 50px)
	*/
}
	
  1. 弹性盒子

    display: flex;
    align-items: center