css元素居中的多個方法
阿新 • • 發佈:2018-12-28
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <style> html, body { /*body 存在邊距*/ margin: 0; width: 100%; height: 100%; } .parentElement { width: 100%; height: 100%; background-color: yellow; } .childElement { background-color: red; width: 100px; height: 100px; } /* 第一種 無相容性問題,但需要知道居中元素的寬和高*/ /*相對定位和固定定位會脫離標準流*/ .parentElement-one { position: relative; } .childElement-one { position: absolute; left: 50%; margin-right: -50px; top: 50%; margin-top: -50px; } /*相容IE10以上*/ /*第二種*/ .parentElement-two { position: relative; } .childElement-two { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } /*第三種*/ .childElement-three { position: relative; left: 50%; top: 50%; transform: translate(-50%, -50%); } /*第四種*/ .parentElement-fore { display: flex; /*垂直方向對齊*/ align-items: center; /*水平方向對齊*/ justify-content: center; } /*相容IE10以上*/ /*第五種 水平居中*/ /*行內元素 設定 text-align:center (文字, 給父元素設定)水平居中*/ /*父元素高度確定的單行文字: height = line-height 垂直居中*/ /*父元素高度確定的多行文字(行內塊): 先設定 display:table-cell 再設定 vertical-align:middle*/ .childElement { /*margin: 0 auto;*/ text-align:center } </style> <body> <div class="parentElement"> <div class="childElement"> <span>dd</span> </div> </div> </body> </html>