盒子水平垂直居中的幾種方法(轉)
.wrapper { width: 500px; height: 300px; background: orange; color: #fff; /只需要在父元素上加這三句/ justify-content: center; /子元素水平居中/ align-items: center; /子元素垂直居中/ display: -webkit-flex; }
二、盒子有固定的寬和高
方案1、margin 負間距
此方案程式碼關鍵點:1.必需知道該div的寬度和高度,
2.然後設定位置為絕對位置,
3.距離頁面視窗左邊框和上邊框的距離設定為50%,這個50%就是指頁面視窗的寬度和高度的50%,
4.最後將該div分別左移和上移,左移和上移的大小就是該DIV寬度和高度的一半。
我知道我的寬度和高是多少,我要實現水平垂直居中。.wrapper { width: 400px; height: 18px; padding: 20px; background: orange; color: #fff; position: absolute; top:50%; left:50%; margin-top: -9px; margin-left: -200px; }
方案2、margin:auto實現絕對定位元素的居中(該方法相容ie8以上瀏覽器)
此方案程式碼關鍵點:1、上下左右均0位置定位;
2、margin: auto;
我不知道我的寬度和高是多少,我要實現水平垂直居中。
.wrapper { width: 400px; height: 18px; padding:20px; background: orange; color: #fff;
position: absolute; left:0; right:0; top: 0; bottom: 0; margin: auto; }