1. 程式人生 > 實用技巧 >讓div水平垂直居中的幾種方法

讓div水平垂直居中的幾種方法

結構層

 <div class='container'>
      <div>123</div>
 </div>

樣式層

.container{
            width: 500px;
            height: 500px;
            margin:0 auto;
            border:1px solid red;
            /* 一 二 三 五樣式 */
            /* position: relative; */
            /* 第四種的樣式 */
            /*
display: flex; justify-content: center; align-items: center; */ /* 第六種樣式 */ /* display: table; */ /* 第七種樣式 */ display: flex; } /* 第一種 */ /* .container div{ width: 100px; height:100px; background:rebeccapurple; position: absolute; left:0; top:0; right:0; bottom:0; margin:auto; }
*/ /* 第二種 */ /* .container div{ width: 200px; height: 200px; background:red; position: absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px; } */ /* 第三種 */ /* .container div{ width: 200px; height: 200px; background:red; position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); }
*/ /* 第四種 彈性佈局*/ /* .container div{ width: 200px; height: 200px; background-color: salmon; } */ /* 第五種 */ /* .container div{ position: absolute; background-color: salmon; width: 200px; height: 200px; left:calc((500px - 200px)/2); top:calc((500px - 200px)/2); left:-webkit-calc((500px - 200px)/2); top:-webkit-calc((500px - 200px)/2); } */ /* 第六種 */ /* .container div{ width: 200px; height: 200px; display: table-cell; vertical-align: middle; text-align: center; background:red; } */ /* 第七種 */ .container div{ width: 200px; height: 200px; background-color: slateblue; margin:auto; }

結果