一、居中元素已知宽高
1、子绝父相 + margin:auto + 四个方向都是0
.parent{
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.child{
position: absolute;
margin: auto;
top: 0;bottom: 0;left: 0;right: 0;
width: 100px;
height: 100px;
background-color: green;
}
2、子绝父相 + 负margin
.parent{
position: relative;
width: 400px;
height: 400px;
background-color: red;
}
.child{
position: absolute;
top: 50%;left: 50%;
/* 这里的负margin取宽高的一半*/
margin-top: -100px;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: green;
}
3、子绝父相 + calc函数
CSS3中的 calc函数
实现原理,与上面类似
.parent{
position: relative;
width: 400px;
height: 400px;
background-color: red;
}
.child{
position: absolute;
top: calc(50% - 100px);
left: calc(50% - 100px);
width: 200px;
height: 200px;
background-color: green;
}
二、居中元素宽高未知
1、子绝父相 + transform:translate(-50%,-50%)
transform 的 translate 属性值如果是一个百分比,那么这个百分比将是基于自身的宽高计算出来的
.parent{
position: relative;
width: 400px;
height: 400px;
background-color: red;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
/*child元素没有设置宽高,可以为文字等行内元素 或 块状元素*/
color: yellow;
background-color: green;
}
2、line-height + vertical-align + text-align
父元素不需要设置高度,高度取决于 line-height
父元素设置 text-align:center 做到子元素水平居中
子元素需设置成 inline-block
子元素line-height: initial; 继承父元素行距
子元素设置 vertical-align: middle; 做到垂直居中
.parent{
text-align: center;
line-height: 200px;
width: 200px;
background-color: red;
}
.child{
display: inline-block;
line-height: initial;
vertical-align: middle;
}
3、table表格元素
表格元素默认 inline元素垂直居中,所以只需要父元素设置 text-align: center 水平居中即可
子元素设置 display: inline-block;
<style>
.parent{
width: 200px;
height: 200px;
background: red;
text-align: center;
}
.child{
background: green;
display: inline-block;
}
</style>
</head>
<body>
<table>
<tr>
<td class="parent">
<div class="child">
这是被居中的元素
</div>
</td>
</tr>
</table>
</body>
4、table-cell
一定要使用table特性,又不想使用table元素时
与上面第三点类似,只是父标签要设置 display:table-cell;
父标签设置 vertical-align:middle做垂直居中\
.parent{
width: 200px;
height: 200px;
background: red;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child{
background: green;
display: inline-block;
}
5、flex + justify-content + align-items
父元素设置弹性布局,然后 水平居中,垂直居中
子元素无需任何设置
.parent{
width: 200px;
height: 200px;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
background: green;
}
6、flex + margin:auto
父元素设置 display:flex
子元素设置 margin:auto
.parent{
display: flex;
width: 200px;
height: 200px;
background: red;
}
.child{
margin: auto;
background: green;
}
总结
- 如果是PC端有兼容要求,并且宽高固定 --> 子绝父相 + 负margin
- 如果是PC端有兼容要求,并且宽高不固定 --> table-cell
- 如果是PC端无兼容要求 --> flex(两种均可)
- 如果是移动端 --> flex(两种均可)