初始html:
<div id="container"> <div id="box"></div> </div>
初始css:
#container{ width: 400px; height: 400px; }
#box{ width: 100px; height: 100px; }
方法一:* margin: auto; *(必須固定父元素大小)
#container{
position: relative;
}
#box{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法二:絕對(duì)定位法 (必須固定父元素大小)
#container{
position: relative;
}
#box{
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
/* 或者 transform: translate(-50%,-50%);這種方法不需要知道子元素的大小 */
}
方法三:table-cell方法(可不設(shè)置父元素大杏钠摺)
#container{
display: table-cell;
vertical-align: middle;
text-align: center;
/*此時(shí)給父元素設(shè)置margin無(wú)效,并且不設(shè)置父元素的寬高只設(shè)置padding也可實(shí)現(xiàn)居中 */
}
#box{
display: inline-block;
}
方法四:flex布局(可不設(shè)置父元素大胁饽ⅰ)
#container{
display: flex;
/* 此時(shí)父元素也可不知大小份帐,僅用padding撐開(kāi)盒子也可居中膏萧,但是這里父元素是塊元素湾笛,要占滿一行 */
}
#box{
margin: auto;
}
/* 或者 */
#container{
display: flex;
justify-content: center;
align-items: center;
}
#box{
}