css div上下左右置中

來源:互聯網
上載者:User

通常我們用到的css布局都是左右置中,經典css寫法如下:

body{    margin:0;    padding:0;    width:100%;    height:100%;}div{    margin:0 auto;    width:500px;    heigth:auto;}

上面是經典的左右置中的css寫法,那麼像登入框那些比較小得div塊只是左右置中是否不是太美觀,如果上下左右都置中這是

大多數網站的做法,下面是一個比較經典的div上下左右置中的css寫法:

body{    margin:0;    padding:0;    width:100%;    height:100%;}div{   position:absolute;   top:50%;   left:50%;   margin-top:-250px;   margin-left:-250px;    /*此時寬和高都要固定*/    width:500px;    heigth:500px;}

上面的margin可以合并:margin:-250px 0 0 -250px;

大概原理就是:布局需用position,絕對布局absolute還是相對布局relative得看父容器,top,left相對於頂部和左部都相距整個容器的50%,然後在利用margin,向上回退div高的50%即:margin-top:-250px

向左回退div寬的50%即:margin-left:-250px

好了大功告成。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.