1. 程式人生 > >如何讓一個盒子垂直居中

如何讓一個盒子垂直居中

方法1:寬度和高度已知的。
思路:
給父元素相對定位
給子元素絕對定位
left: 50%;top: 50%;
margin-left: 負的寬度一半。
margin-top: 負的高度一半;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>居中</title>
    <style type="text/css">
        #box{
            width: 400px;
            height
: 200px
; position: relative; background: red; }
#box1{ width: 200px; height: 100px; position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-top: -50px; background
: green
; }
</style> </head> <body> <div id="box"> <div id="box1"> </div> </div> </body> </html>

方法2:寬度和高度自己未知
意思就是說子盒子本身還是有寬度和高度的,只是自己未知。
思路:
給父盒子相對定位
給子盒子絕對定位
top、right、bottom、left全為0
margin: auto;

<!DOCTYPE html>
<html> <head> <meta charset="utf-8"> <title>居中</title> <style type="text/css"> #box{ width: 800px; height: 400px; position: relative; background: red; } #box1{ width: 100px; height: 50px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background: green; } </style> </head> <body> <div id="box"> <div id="box1"> </div> </div> <script type="text/javascript"></script> </body> </html>

方法3:flex佈局

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>垂直居中</title>
    <style type="text/css">
        .box{
            width: 400px;
            height: 200px;
            background: #f99;
        }
        .box1{
            width: 200px;
            height: 100px;
            background: green;
        }
        .center{
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class="box center">
        <div class="box1">

        </div>
    </div>
</body>
</html>

方法四:平移

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>css3讓一個盒子居中</title>
    <style type="text/css">
        .parent_box{
            width: 400px;
            height: 200px;
            background: red;
            position: relative;
        }
        .child_box{
            width: 200px;
            height: 100px;
            background: #9ff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate( -50%,-50%);
        }
    </style>
</head>
<body>
    <div class="parent_box">
        <div class="child_box">

        </div>
    </div>
</body>
</html>