1. 行内元素居中
水平:text-align:center;
垂直:line-height:父元素高度;
2. 块级元素居中
水平垂直的居中道理都相同,实现思路以下几种:
(1)定位布局:绝对定位+相对定位+margin:auto (推荐)
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
position: relative;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
(2)定位布局:绝对定位+相对定位+trasform(推荐)
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
position: relative;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
(3)定位布局:绝对定位+相对定位+计算长度
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
position: relative;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
position: absolute;
/* 父width/2 - 子width/2 */
left: 100px;
top: 50px;
}
(4)padding/margin/trasform:计算长度
padding:
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
/* 父width/2 - 子width/2 */
box-sizing: border-box;
padding-left: 100px;
padding-top: 50px;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
}
margin:
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
border: solid 1px black;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
/* 父width/2 - 子width/2 */
margin-left: 100px;
margin-top: 50px;
}
trasform:
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
transform: translate(100px,50px);
}
(5)flex布局:justify-content、align–items(推荐)
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
}
(6)flex布局:auto(推荐)
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
display: flex;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
margin: auto;
}
(7)table-cell:垂直水平分开实现
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
/* 实现垂直居中*/
display: table-cell;
vertical-align: middle;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
/* 实现水平居中 */
margin: auto;
}
(8)table-cell:子设为inline-block
.outer{
background-color: antiquewhite;
width: 500px;
height: 300px;
display: table-cell;
/* 实现垂直居中*/
vertical-align: middle;
/* 实现水平居中 */
text-align: center;
}
.inner{
background-color: aquamarine;
width: 300px;
height: 200px;
display: inline-block;
}
比较好用的是(1)(5)