1. 程式人生 > 實用技巧 >左右固定寬度中間自適應佈局方式

左右固定寬度中間自適應佈局方式

話不多說先上要實現的效果:(很簡單水平居中)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>左右固定中間自適應</title>
    </head>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }
/* 方式一:浮動 */ .box{ height: 200px; background: #000000; } .left{ width: 100px; height: 100%; background: #21759B; float: left; } .main{ margin: 0 100px; height: 100%; background
: #ccc; } .right{ width: 100px; height: 100%; background: #21759B; float: right; } </style> <body> <div class="box"> <p style="color:#fff">Tip:html方面,必須中間在最後,不然右邊就會擠下來【dom的渲染機制的問題】</
p> <div class="right">右邊固定</div> <div class="left">左邊固定</div> <div class="main">中間自適應</div> </div> </body> </html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>左右固定中間自適應</title>
    </head>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        /* 方式二:定位 */
        .box{
            background: #000000;
            position: relative;
        }
        .left{
            width: 100px;
            height: 100%;
            background: #21759B;
            position: absolute;
            top: 0;
            left: 0;
        }
        .main{
            margin: 0 100px;
            height: 200px;
            background: #ccc;
        }
        .right{
            width: 100px;
            height: 100%;
            background: #21759B;
            position: absolute;
            top: 0;
            right: 0;
        }
    </style>
    <body>
        <div class="box">
            <div class="left">左邊固定</div>
            <div class="main">中間自適應</div>
            <div class="right">右邊固定</div>
        </div>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>左右固定中間自適應</title>
    </head>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        /* 方式三:flex */
        .box{
            display: flex;
            height: 200px;
            background: #000000;
        }
        .left{
            width: 100px;
            height: 100%;
            background: #21759B;
        }
        .main{
            flex: 1;
            height: 100%;
            background: #ccc;
        }
        .right{
            width: 100px;
            height: 100%;
            background: #21759B;
        }
    </style>
    <body>
        <div class="box">
            <div class="left">左邊固定</div>
            <div class="main">中間自適應</div>
            <div class="right">右邊固定</div>
        </div>
    </body>
</html>