1.子元素相对于父元素绝对定位,并且margin值减去自己宽高的一半
该方法具有一定的局限性,因为其必须要知道子元素本身的宽高
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
position: relative;
}
item{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100x;
background: green;
}
2.子元素相对于父元素绝对定位,并且margin值为auto
该方式不受元素宽高所限制
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
position: relative;
}
item{
position: absolute;
left: 0;
right: 0;
bottom: 0;
top:0;
margin: auto;
width: 100px;
height: 100x;
background: green;
}
3.diplay:table-cell
该方式是将元素转换成表格样式,再利用表格的样式来进行居中
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
display: table-cell;
vertical-align: middle;
}
item{
margin:0 auto;
width: 100px;
height: 100x;
background: green;
}
4.绝对定位和transfrom
该方法用到了常CSS3的属性,当然存在兼容性问题
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
position:relative;
}
item{
width: 100px;
height: 100x;
background: green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
5.css3中的flex属性
同样存在兼容性问题
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
item{
width: 100px;
height: 100x;
background: green;
}