一、对于行内元素
div{text-align:center} /*DIV内的行内元素均会水平居中*/
二、对于宽度width确定的块状元素
1、前提是已经设置了width
{
margin-left:auto;
margin-right:auto;
}
2、绝对定位减掉自身宽度
{
width:200px;
height:50px;
position:absolute;
left:50%;
margin-left:-100px;//自身宽度的一半
}
3、绝对定位,上下左右绝对0,margin:auto,垂直水平居中
{
position: absolute;
width: 200px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
三、对于宽度未知的块状元素
1、绝对定位+transform,translateX移动元素的50%
{
position: absolute;
left: 50%;
transform: translateX(-50%); /* 移动元素本身50% */
background: orange;
}
2、css3的fit-content属性配合左右margin为auto
{
width: fit-content;
margin-left: auto;
margin-right: auto;
}