CSS-佈局2-中間固定兩邊自適應

java小工匠發表於2017-07-12

1、佈局概述

中間固定,兩邊自適應佈局,這是一種非常罕見的佈局。例如下圖,測試劇中,這幾個字固定寬度,左右的紅線根據螢幕自適應。

image.png

2、實現思路1- 浮動加負邊距

實現思路
(1) 建立左中右3個div。
(2)左邊div各佔50%寬度;左邊div的左邊負邊距,設定為中間div寬度的一半。
(3)右邊div各佔50%寬度;右邊div的右邊負邊距,設定為中間div寬度的一半。
原始碼:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>中間固定寬度,兩邊自適應佈局-浮動加負邊距</title>
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;

        }
        .wrap{
            overflow: hidden;
            margin-top: 20px;
        }
        .center{
           width: 70px;
           text-align: center;
           float: left;
     
        }
        .left{
            line-height: 30px;
            height: 30px;
            float: left;
            width: 50%;
            margin-left: -35px;
        }
        .right{
            line-height: 30px;
            height: 30px;
            float: right;
            width: 50%;
            margin-right: -35px;
        }
        hr{ height:1px;border:none;border-top:1px solid red;}
    </style>
</head>
<body>
    <div class="wrap">
        <div class="left">
            <hr style="margin-top: 14px;">
        </div>
        <div class="center">測試居中</div>
        <div class="right">
            <hr style="margin-top: 14px">
        </div>
    </div>
     
</body>
</html>

執行效果:

image.png

刪除中間div後,執行效果:

image.png

3、實現思路2-彈性合作模型

實現思路:
(1) 建立左中右3個div。
(2) 設定負div為彈性盒子模型。
(3) 設定左右div的flex-grow 為1 。
原始碼:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>中間固定寬度,兩邊自適應佈局-彈性盒子模型</title>
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;

        }
        .wrap{
            display: flex;
            flex-direction: row;
            margin-top: 20px;
        }
        .center{
           width: 70px;
           text-align: center;

        }
        .left,.right{
            flex-grow: 1;
            line-height: 30px;
            height: 30px;
        }
        hr{ height:1px;border:none;border-top:1px solid red;}
    </style>
</head>
<body>
    <div class="wrap">
        <div class="left">
            <hr style="margin-top: 14px">
        </div>
        <div class="center">測試劇中</div>
        <div class="right">
            <hr style="margin-top: 14px">
        </div>
    </div>
     
</body>
</html>

4、實現類似顯示效果。

如果只實現類似的顯示效果。另外一種實現思路。
(1) 設定div 的行高為1px。
(2) 設定div 的左邊框、右邊框 寬度為1px solid red;
(3 ) 方案缺點: 不能左右自動適應,只能應用固定寬度的需求。

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>通過高度為1px,設定左右邊框寬寬</title>
    <style type="text/css">
        .wrap{
            width: 500px;
        }
        .nav{
            text-align: center;
            border-left : 200px solid red;
            border-right: 200px solid red;
            line-height : 1px;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="nav">測試劇中</div>
    </div>
</body>
</html>


相關文章