Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 实现一个元素水平垂直居中的方法★★★★

实现一个元素水平垂直居中的方法★★★★

重要程度★★★★

1.absolute + 负margin

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

2.absolute + margin auto

.parent {
	position:relative;
}

.son {
	position:absolute;
	left:0;
	top:0;
	right:0;
	bottom:0;
	margin:auto;
}

3.flex

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

4.absolute + calc

.parent {
	position:relative;
}
.son {
	position:absolute;
	width:100px;
	height:100px;
	left:calc(50% - 50px);
	top:calc(50% - 50px);
}

5.absolute + transform

.parent {
	position:relative;
}
.son {
	position:absolute;
	left:50%;
	top:50%;
	transform:translate(-50%,-50%);
}

6.css-table

.parent {
	display:table-cell;
	text-align:center;
	vertical-align:middle;
}
.son {
	display:inline-block;
}

7.grid

.parent {
	display:grid;
}

.son {
	align-self:center;
	justify-self:center;
}
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人