一:水平居中
(1) : margin:0 auto; (块级居中)
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
margin: 0 auto;
}
</style>
<div class="box">
<div class="box1"></div>
</div>
效果图:
(2) : text-align: center;(行内居中)
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
text-align: center;
}
span {
background-color: orange;
}
</style>
<div class="box">
<span>我是span</span>
</div>
效果图:
(3) : position:absolute +left:50% + transform:translateX(-50%)
记的子绝父相哦
<style>
.box {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.box2 {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="box">
<div class="box2"></div>
</div>
效果图:
(4) : display:flex + justify-content: center
<style>
.box {
display: flex;
justify-content: center;
width: 200px;
height: 200px;
background-color: pink;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="box">
<div class="box2"></div>
</div>
效果图:
二:垂直居中
(1) : line-height等于元素的高度
<style>
.box {
width: 100px;
height: 40px;
background-color: pink;
}
span{
line-height: 40px;
background-color: orange;
}
</style>
<div class="box">
<span>我是span</span>
</div>
效果图:
(2) : position:absolute +top:50%+ transform:translateY(-50%)
<style>
.box {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.box1 {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="box">
<div class="box1"></div>
</div>
效果图:
(3) : display:flex + align-items: center
<style>
.box {
display: flex;
align-items: center;
width: 200px;
height: 200px;
background-color: pink;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<div class="box">
<div class="box1"></div>
</div>
效果图:
(4) : display:table + ( display:table-cell + vertical-align: middle; )
<style>
.box {
display: table;
width: 200px;
height: 200px;
background-color: pink;
}
span {
display: table-cell;
vertical-align: middle;
}
</style>
<div class="box">
<span>我是span,我想要垂直居中</span>
</div>
效果图:
按照自己的需求来使用,结合使用可实现水平垂直居中,还有其他方法欢迎来补充