css中的常見佈局面試題

漂亮得皮皮發表於2018-09-12
雙飛翼和聖盃佈局區別可參考:
https://www.cnblogs.com/imwtr/p/4441741.html

一、固定佈局

二、自適應佈局
寬度隨著網頁大小的改變而改變;

三、常見型別

1、兩列布局:

1.1 左邊寬度固定,右邊寬度自適應(左邊浮動,下一個元素就會佔據位置,並排一行)

.main {/*外層的樣式:父級元素的水平居中*/width: 95%;margin-left:auto;margin-right:auto;/* 左右居中 */}
/*左邊設定固定寬度以及左浮動(為了不佔一行)*/.left {float: left;width: 200px;height: 600px;background: red;}
/*右邊設定自適應寬度,最小寬度,margin-left,把左邊固定寬度的元素的位置留出來就好了*/
.right {min-width: 400px; /* 最小寬度 */margin-left: 210px;//不設定margin,左邊欄和右邊欄會有重合部分height: 600px;background: blue;}複製程式碼

html:

<div class="main"><div class="left"></div><div class="right"></div></div>複製程式碼


1.2、右邊寬度固定,左邊寬度自適應:左右都浮動(左邊自適應元素設定外層div 100%寬度,這樣會佔一行,然後裡層設定右邊的margin,把右邊元素位置空出來)

//左邊父級設定100%寬度,左浮動.left-fa {width: 100%;//佔一行float: left;}//左邊子元素設定margin-right.left {margin-right: 310px;//把右邊固定寬度的元素位置留出來height: 600px;background: red;}/*右邊固定寬度的元素左浮動,和margin-left負的本身大小*/.right {width: 300px;height: 600px;background: yellow;float: left;margin-left: -300px; //設定本身寬度的負值,是為了和左邊元素佔一行,不設定就被擠在下一行}複製程式碼


2、三列布局

2.1 定位法:(左右邊設定絕對定位,設定一個最外級div(給父級設定relative,相對最外層定位))

.main {//最外層width: 95%;margin-left:auto;margin-right:auto;/* 左右居中 */height: 300px;*zoom: 1;position: relative;}
/*左邊固定元素定位*/.left{position: absolute;top: 0;left: 0;width: 200px;height: 100%;background-color: cyan;}
/* 中間自適應,設定的margin左右距離為左右二邊固定寬度元素的 大小*/.center-fa{width: 100%;height: 100%;}.center{height: 100%;min-width: 400px;margin-left: 210px;margin-right: 210px;background-color: chocolate;}
.right{position: absolute;top: 0;right: 0;width: 200px;height: 100%;background-color: rgb(255, 0, 221);}
複製程式碼

html:

<div class="main"><div class="left"></div><div class="center-fa"> <div class="center"></div></div><div class="right"></div></div>
複製程式碼

2.1 雙飛翼佈局(對比聖盃如何呢??):(三欄都浮動,中間自適應元素設定外層div 100%寬度,以防獨佔一行,裡層需要設定左右固定二欄的margin寬度,把左右二欄的位置空出來;另外,三欄排成一排,左右二欄需要設定負margin自身寬度)

.main {width: 95%;margin-left:auto;margin-right:auto;/* 左右居中 */height: 300px;overflow: hidden;*zoom: 1;}.left{float: left;width: 200px;height: 100%;margin-right: -200px;/*負margin自身寬度,為了並排一行。不然下面的會一直被擠下去*/background-color: cyan;}.center-fa{float: left;width: 100%;height: 100%;}.center{height: 100%;min-width: 400px;margin-left: 210px;/*為了給左右二欄空出位置*/margin-right: 210px;background-color: chocolate;}
.right{margin-left: -200px;/*負margin自身寬度,為了並排一行*/float: left;width: 200px;height: 100%;background-color: rgb(255, 0, 221);}
複製程式碼

html:

<div class="main"><div class="left"></div><div class="center-fa"><div class="center"></div></div><div class="right"></div></div>
複製程式碼


相關文章