CSS佈局(五)
前言
如何快速的用html寫出一個界面,你可能會覺得很簡單,不就是div擺放,表格佈局然後調整下樣式嗎,可真正做的時候有各種居中、浮動等,並且還要考慮到樣式兼容、屏幕分辨率等問題。目前CSS佈局主要有如下技術:
- 浮動
- 定位
- CSS表格
- flex佈局(彈性佈局、彈性盒子)
- 網格
- 框架
浮動
所謂浮動就是允許元素浮動到另外一個元素的左側或者右側,浮動的框會脫離文檔流,也就是他本該佔據的位置會空出來。
float 屬性有四個可能的值:
1. left — 將元素浮動到左側。
2. right — 將元素浮動到右側。
3. none — 默認值, 不浮動。
4. inherit — 繼承父元素的浮動屬性。
框1右浮動,脫離文檔流,直到碰到另一個元素的邊緣。
再請看下圖,當框 1 向左浮動時,它脫離文檔流並且向左移動,直到它的左邊緣碰到包含框的左邊緣。因爲它不再處於文檔流中,所以它不佔據空間,實際上覆蓋住了框 2,使框 2 從視圖中消失。
如果把所有三個框都向左移動,那麼框 1 向左浮動直到碰到包含框,另外兩個框向左浮動直到碰到前一個浮動框。
如下圖所示,如果包含框太窄,無法容納水平排列的三個浮動元素,那麼其它浮動塊向下移動,直到有足夠的空間。如果浮動元素的高度不同,那麼當它們向下移動時可能被其它浮動元素“卡住”:
定位
定位是通過position屬性,常用的四種定位類型有:
- 靜態定位(Static positioning):是每個元素默認的屬性——它表示“將元素放在文檔佈局流的默認位置——沒有什麼特殊的地方”。
- 相對定位(Relative positioning):相對於它原始位置進行偏移等操作,沒有脫離文檔流。
- 絕對定位(Absolute positioning):絕對定位會使元素脫離正常佈局流的控制,也就是可以隨心所欲的放在哪兒。.
- 固定定位(Fixed positioning):顧名思義就是固定元素在某一個地方(如:網頁的置頂按鈕)。
eg:
HTML代碼
<h1>Basic document flow</h1>
<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p>
CSS代碼
body {
width: 500px;
margin: 0 auto;
}
p {
background: aqua;
border: 3px solid blue;
padding: 10px;
margin: 10px;
}
span {
background: red;
border: 1px solid black;
}
正常佈局流效果
相對定位
1、新增CSS代碼
.positioned{
position: relative;
top: 30px;
left: 30px;
}
2、效果
可以看到黃色部分設置相對定位後,在它正常的佈局流中往上和往左偏移了30px。
CSS表格(不怎麼用)
不要誤以爲表格佈局不是利用table標籤的tr或者td進行佈局,而是display屬性設置爲table、table-row……等屬性。
flex佈局
非常靈活,可參考超級詳細的一篇文章flex佈局
網格佈局(TODO)
框架
利用框架的話就是bootstrap框架了,主要是它的柵格系統。