版权声明, 本文内容源自(https://javascript.plainenglish.io/dear-developer-this-is-how-you-center-a-div-e526e7cfcc9d)
<div class="container">
<div class="content">I'm centered</div>
</div>
常见的有三种方法:
1. 使用绝对定位
.container {
position: relative;
}.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
或者
.container {
position: relative;
}.content {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom:0;
margin:auto;
}
2. 使用flex
display: flex;
align-items:center;
justify-content:center;
3. 使用grid
display: grid;
place-items: center;