徹底弄懂聖盃佈局(margin-left=-100%的)

首先,html頁面代碼結構如下

<div style="width: 1000px">
    <div id="container">
        <div id="center">中間的</div>
        <div id="left">左邊的</div>
        <div id="right">右邊的</div>
    </div>
</div>

這裏設置容器寬度爲50%是爲了更好的演示

首先設置容器css樣式

    #container{
        width: 50%;
        height: 720px;
        background-color: pink;
        padding:0 200px 0 100px;
    }

得到頁面效果如下

因爲background的顏色在內邊距中也有效,可能你看不出我已經在中間挖了一個槽,這個槽距離左邊界爲100px;右邊界爲200px;接下來我讓這個槽更加明顯一點。在左右中三欄中我們優先選擇渲染中間欄

    #center{
            width: 100%;
            height: 600px;
            float: left;
            background-color: blue;
        }

此時頁面效果如下所示

然後渲染左右兩欄

        #left{
            float: left;
            width: 100px;
            height: 600px;
            background-color: rebeccapurple;
        }
        #right{
            float: left;
            width: 200px;
            height: 600px;
            background-color: lightgray;
        }

 

這時我們看到,由於中間欄的寬度設置成了100%,左右兩欄被擠了下去。我們用負外邊距的方法將左右兩欄提上來。

css代碼如下

        #left{
            margin-left: -100%;
            float: left;
            width: 100px;
            height: 600px;
            background-color: rebeccapurple;
        }
        #right{
            margin-right: -200px;
            float: left;
            width: 200px;
            height: 600px;
            background-color: lightgray;
        }

此時效果如下

可以看到我們基本已經完成了,只是左邊欄沒有到應有的位置,需要平移,相對於自身位置平移最好的方法就是relative定位了。

給left加上平移

        #left{
            position: relative;
            left: -100px;
            margin-left: -100%;
            float: left;
            width: 100px;
            height: 600px;
            background-color: rebeccapurple;
        }

問題來了問題來了?

爲什麼left不和right一樣直接設置個margin-left一步到位呢?

我們首先理解一下margin-left的字面意思。

在同級之間,它是指元素的右外邊距和其右邊元素的左外邊距的距離。

在父子之間,它是指元素的左外邊距和其父級元素的左內邊距的距離。

差別。我們首先先回到這一步時的頁面情況

如果我們想把紫色的這一塊放到它應該有的位置,那麼margin-left應該設置成什麼?父子元素,margin-left設置的是元素的左外邊距和父元素的右內邊距的距離。那麼我們如果想把紫色放到藍色的左邊,看圖示

所以margin-left應該設置成負的150+藍色區域的寬度!但是問題出現了。藍色區域的寬度是自適應的,也就是說是可變的。所以我們如果要實現三欄佈局。只能使用position:relative來曲線救國啦。

 

測試效果

 

最終的css代碼如下

        #container{
            width: 50%;
            background-color: pink;
            height: 700px;
            padding: 0 200px 0 100px;
        }
        #center{
            width: 100%;
            height: 600px;
            float: left;
            background-color: blue;
        }
        #left{
            position: relative;
            left: -100px;
            margin-left: -100%;
            float: left;
            width: 100px;
            height: 600px;
            background-color: rebeccapurple;
        }
        #right{
            margin-right: -200px;
            float: left;
            width: 200px;
            height: 600px;
            background-color: lightgray;
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章