1.利用 position:absolute
<div class="father">
<div class="son"></div>
</div>
- 当已知元素宽度和高度时,可以设置
position: absolute
和margin
为负的宽高的一半
<style>
.father{
position: relative;
background-color: pink;
width: 200px;
height: 200px;
}
.son{
position: absolute;
background-color: red;
width:50px;
height: 50px;
left: 50%;
top: 50%;
margin-top: -25px;
margin-left: -25px;
}
</style>
- 当元素宽度和高度未知时,可以设置
position: absolute
和transform: translate(-50%, -50%)
.father{
position: relative;
background-color: pink;
width: 200px;
height: 200px;
}
.son{
position: absolute;
width: 50px;
height: 50px;
background-color: red;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
2. 利用margin:auto
.father{
position: relative;
background-color: pink;
width: 200px;
height: 200px;
}
.son{
position: absolute;
background-color: red;
width: 50px;
height: 50px;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
3. 利用弹性盒子
通过给父元素设置display:flex
来实现居中
.father{
display: flex;
justify-content: center; //主轴
align-items: center; //侧轴
background-color: pink;
width: 200px;
height: 200px;
}
.son{
background-color: red;
width: 50px;
height: 50px;
}
4. 利用水平对齐和行高
设置text-align:center
和line-height:height
实现单行文本水平垂直居中
<div class="father">
<div class="son">我要居中</div>
</div>
.father{
background-color: pink;
width: 200px;
height: 200px;
text-align: center;
}
.son{
line-height: 200px;
}
5. 最简便的方法
flex+auto
父元素设置flex 子元素margin:auto;
<style>
.g-container{
display: flex;
width: 300px;
height: 300px;
background-color:aqua;
}
.g-box{
margin: auto;
width: 100px;
height: 100px;
background-color: black;
}
</style>
<body>
<div class="g-container">
<div class="g-box"></div>
</div>
</body>