作者:方偉景
鏈接:https://zhuanlan.zhihu.com/p/39437057
來源:知乎
著作權歸作者所有霍骄。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權在旱,非商業(yè)轉(zhuǎn)載請注明出處谢鹊。
第一種:利用負的margin來進行居中,需要知道固定寬高瘸洛,限制比較大蚓再。
body>div:nth-of-type(1){ width:400px; height:400px; background:#ff0; position:relative; margin-bottom:10px;}
body>div:nth-of-type(1)div{ width:100px; height:100px; background:#0f0; position:absolute; top:50%; left:50%; margin-left:-50px; margin-top:-50px;}
第二種:利用絕對定位居中,非常常用的一種方法一姿。body>div:nth-of-type(2){ width:400px; height:400px; background:#ff0; position:relative; margin-bottom:10px;}
body>div:nth-of-type(2) div{ width:100px; height:100px; background:#0f0; position:absolute; top:0; left:0; right:0; bottom:0; margin:auto;}
第三種:使用flex布局(.min寬高可不固定)
body>div:nth-of-type(3){ width:400px; height:400px; background:#ff0; margin-bottom:10px; display:flex;}
body>div:nth-of-type(3) div{ width:100px; height:100px; background:#0f0; margin:auto }
第四種:flex居中(演示)七咧。CSS3中引入的新布局方式改执,比較好用。缺點:IE9以及IE9一下不兼容坑雅。
body>div:nth-of-type(4){ width:400px; height:400px; background:#ff0; margin-bottom:10px; display:flex; justify-content:center;align-items:center}
body>div:nth-of-type(4) div{ width:100px; height:100px; background:#0f0; }
第五種:利用table-cell來控制垂直居中辈挂。
body>div:nth-of-type(5){ width:400px; height:400px; background:#ff0; margin-bottom:10px; vertical-align:middle; display:table-cell; text-align:center;}
body>div:nth-of-type(5) div{ width:100px; height:100px; background:#0f0; display:inline-block }
第六種:利用空盒子做外容器,里邊的塊元素會自動垂直居中裹粤,只需要控制一下水平居中就可以達到效果终蒂。
body>div:nth-of-type(6){ width:400px; height:400px; background:#ff0; margin-bottom:10px; text-align:center;?vertical-align:middle;}
body>div:nth-of-type(6) div{ width:100px; height:100px; background:#0f0; display:inline-block; vertical-align:middle; }
body>div:nth-of-type(6) span{ width:0; height:100%; display:inline-block; vertical-align:middle;}
第七種:這種方法靈活運用CSS中transform屬性,較為新奇遥诉。缺點是IE9下不兼容拇泣。
body>div:nth-of-type(7){ width:400px; height:400px; background:#ff0; position:relative; margin-bottom:10px;}
body>div:nth-of-type(7) div{ width:100px; height:100px; background:#0f0; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%)}