1. 水平居中
<div class="father">
<div class="son">水平居中</div>
</div>
1.
.father {
text-align: center;
}
.son {
background: red;
}
2.
.son {
width: 200px;
background: red;
margin: 0 auto;
}
3.
.son {
display: table;
margin: 0 auto;
background: red;
}
4.
.father {
text-align: center;
}
.son {
display: inline-block;
}
5.
.father {
display: flex;
justify-content: center;
}
2. 垂直居中
<div class="father">
<div class="son">垂直居中</div>
</div>
1.
.father {
height: 100px;
background: red;
}
.son {
line-height: 100px;
}
2.
.father {
height: 100px;
background: red;
display: table;
}
.son {
display: table-cell;
vertical-align: middle;
}
3.
.father {
background: yellow;
height: 200px;
display: flex;
align-items: center;
}
4.
.father {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #000;
}
.son {
background: red;
width: 100px;
height: 100px;
line-height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
}
5.
.father {
width: 200px;
height: 200px;
position: relative;
border: 1px solid #000;
}
.son {
width: 100px;
height: 100px;
position: absolute;
top: 0;
bottom: 0;
margin: auto;
background: red;
}
6.
.father {
width: 200px;
height: 200px;
position: relative;
border: 1px solid #000;
}
.son {
width: 100px;
height: 100px;
position: absolute;
top: 50%;
transform: translate(0,-50%);
background: red;
}
3. 水平垂直居中
<div class="father">
<div class="son">水平垂直居中</div>
</div>
.father {
display: flex;
justify-content: center;
align-items: center;
}
.father {
position: relative;
}
.son {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
.father {
position: relative;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
.father {
width: 200px;
height: 200px;
position: relative;
}
.son {
width: 10px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;;
margin-left: -50px;
}
.father {
width: 200px;
height: 200px;
display: table-cell;
text-align: center;
vertical-align: middle;
border: 1px solid #000;
}
.son {
background: green;
display: inline-block;
}
.father {
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
width: 200px;
height: 200px;
background-color: orange;
text-align: center;
}
.son {
width: 100px;
height: 100px;
line-height: 100px;
background-color: red;
}