- margin: 0 auto;水平
- text-align: center;水平
- 行高,垂直
- 绝对定位,50%减自身宽高
.conter{
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
或者
.conter{
width: 600px; height: 400px;
position: absolute; left: 50%; top: 50%;
transform: translate(-50%, -50%); /* 50%为自身尺寸的一半*/
/* translate平移,参考自己的位置来平移 */
}
- 绝对定位,上下左右全0,margin:auto
.conter{
width: 600px; height: 400px;
position: absolute; left: 0; top: 0; right: 0; bottom: 0;
margin: auto; /* 有了这个就自动居中了 */
}
- 绝对定位加相对定位。不需要知道宽高
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
居中
</div>
</div>
</body>
- flex布局定位居中。这种情况是在不考虑低版本浏览器的情况下可以使用。
.box {
display: flex;
align-items: center ;/* 属性定义项目在交叉轴上如何对齐 */
justify-content: center;/* 属性定义了项目在主轴上的对齐方式 */
}