HTML 代码部分
块级元素
<div class="parent">
<div class="child">child</div>
</div>
行内元素
<div class="parent">
<span class="child">child</span>
</div>
水平垂直居中
1、行内元素
.parent {
text-align: center;
line-height: 50px;
height: 50px;
}
2、flex
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
justify-content: center;
}
优点:更灵活,也更简洁,可维护性也更强。只要不考虑IE,这个方案几乎是最优选择吧。
缺点:如果还在使用IE浏览器的话,flex布局就没那么香了。
3、绝对定位 + margin: auto;
.parent {
position: relative;
height: 200px;
border: 1px solid red;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
border: 1px solid green;
}
优点:不需要提前知道尺寸,兼容性好.
缺点:目前已经不建议使用绝对定位 absolut了,如果还在用IE开发,这个方法还是比较推荐的。
4、绝对定位(已知宽高)
.parent {
position: relative;
height: 200px;
border: 1px solid red;
}
.child {
width: 80px;
height: 40px;
border: 1px solid green;
position: absolute;
left: 50%;
top: 50%;
margin-top: -20px;
margin-left: -40px;
}
缺点:
1、需要提前知道 child 的尺寸,margin-top: -(高度的一半); margin-left: -(宽度的一半);
2、现在已经不建议使用绝对定位 absolute,特别是在移动设备上。
优点: 兼容性不错,也算是一点小技巧吧。
5、绝对定位(未知宽高)
.parent {
position: relative;
height: 200px;
border: 1px solid red;
}
.child {
width: 80px;
height: 40px;
border: 1px solid green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
优点:不需要提前知道尺寸
缺点:兼容性一般般
6、grid
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: grid;
}
.child {
justify-self: center;
align-self: center;
border: 1px solid pink;
}
7、table
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
这样也行
<table>
<tr>
<td align="center" valign="middle">content</td>
</tr>
</table>