1. 程式人生 > 其它 >絕對定位元素的位置

絕對定位元素的位置

 <style>         .box1{             width: 600px;             height: 600px;             background-color: #bfa;             position: relative ;         }         .box2{             width: 100px;             height: 100px;             background-color: tomato;             position: absolute ;             left: 0;
            right: 0;             top: 0;             bottom: 0;             margin: auto;             /*             水平佈局:                 left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-right + right             -當我們開啟了絕對定位後:                 水平方向的佈局等式就需要多加兩個值:left right                     此時規則和之前一樣只是多加了兩個值:                         當發生過度約束:                             如果九個值中沒有 auto 則自動調整 right
以使等式滿足                             如果有auto,則自動調整 auto 的值以使等式滿足                 -可設定的auto的值:                 margin width left right                         -因為 left和 right 的預設值是 auto,所以如果不知道 left和right              則等式不滿足時,會自動調整他們的值                          垂直方向的佈局的等式也要滿足:                 top + margin-top/bottom + padding-top/bottom + height + top +bottom                                                         */                 }



    </style> </head>     <body>     <div class="box1">         <div class="box2"></div>     </div> </body>   根據絕對定位,可以得到一個使子元素垂直水平居中的辦法,既程式碼中綠色部分,將 top,bottolm,left,right 設定為 0,margin 設定為auto 但別忘記 absolute 是參考包含塊進行定位的,所以父元素需要開啟定位,如 relative