1. 程式人生 > 實用技巧 >利用絕對定位實現水平垂直居中

利用絕對定位實現水平垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        .box1
{ width: 500px; height: 500px; background-color: #bfa; position: relative; } .box2{ width: 100px; height: 100px; background-color: orange; position: absolute; margin: auto; /*
水平佈局 left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-right + right = 包含塊的內容區的寬度 - 當我們開啟了絕對定位後: 水平方向的佈局等式就需要新增left 和 right 兩個值 此時規則和之前一樣只是多添加了兩個值: 當發生過度約束: 如果9個值中沒有 auto 則自動調整right值以使等式滿足 如果有auto,則自動調整auto的值以使等式滿足 - 可設定auto的值 margin width left right - 因為left 和 right的值預設是auto,所以如果不指定left和right 則等式不滿足時,會自動調整這兩個值 垂直方向佈局的等式的也必須要滿足 top + margin-top/bottom + padding-top/bottom + border-top/bottom + height = 包含塊的高度
*/ left: 0; right: 0; top: 0; bottom: 0; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>