金魚也能學會寫網頁-基本版面設計、盒子模型

一開始只是興趣使然,寫了一篇關於網頁框架的簡單筆記,不過幾經思考後,還是想把它寫成網頁相關的系列筆記,希望在忘了一些東西時,能有個地方可以快速找回記憶。☺️

💡 Hint: 以下筆記內容所使用的作業系統為"Windows 10"

📝 float 的基本概念

float 在 CSS 中是最基本的版面設計技巧,不瞭解 float 的話,就很難利用 CSS 來進行版面的規劃設計。

不設定 float (預設)

網頁中的每個區塊會由上往下顯示。

設定 float: left;

原本區塊會由上往下顯示,設定後會變成由左往右排列顯示。

設定 float 的區塊通常都要指定 width,若是 width 不足,超過的部分會被強制放到下一行,造成版面錯置。

設定 float: right;

原本區塊會由上往下顯示,設定後會變成由右往左排列顯示,原始碼最上方的區塊會排在最右邊。

解除"文繞圖"

只有部分區塊有設定 float 時,在 float 區塊的後續元素可能會因為上方還有空間硬擠上來,產生"文繞圖"的效果。

在 float 之後的區塊上加上 clear 屬性,就可以解除文繞圖回復預設由上往下排列顯示。

基本上 float 和 clear 會被當作一組成對的指令。

版面設計實例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>網頁標題</h1>
<div>
<div class="box">
<img class="picture" src="https://picsum.photos/seed/157/500/300" alt="">
<dl class="data">
<dt>地點:</dt>
<dd>說明文字</dd>
<dt>簡介:</dt>
<dd>說明文字</dd>
</dl>
<img class="picture" src="https://picsum.photos/seed/111/500/300" alt="">
<dl class="data">
<dt>地點:</dt>
<dd>說明文字</dd>
<dt>簡介:</dt>
<dd>說明文字</dd>
</dl>
</div>
</div>
<style>
body{
background-color: #fff6e6;
}
h1{
text-align: center;
margin-bottom: 30px;
}
.box{
width: 960px;
}
.picture{
float: left;
margin-bottom: 30px;
margin-right: 30px;
}
.data{
float: left;
}
dt{
clear: left;
float: left;
}
</style>
</body>
</html>

盒子模型 (box model)

定義:
The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model.

簡單來說平常寫的<p>lorem...</p>,就可以看做是一個Box,而Box Model則規範Box在瀏覽器上的長相。

盒子模型的 width/height、margin、border、pading 等屬性值間的關係,共同構成了所謂的盒子模型。

熟悉盒子模型的概念後,才有辦法進一步規劃、計算整個版面的尺寸。

  • 盒子模型概念圖

width/height: 內容顯示區域(content-box)的寬、高
boder: 邊框
margin: 外部間距
padding: 內部間距

實際上眼睛所見寬度 = border + padding + width

實際上眼睛所見高度 = border + padding + height

💡 Hint: 當 padding 或 border 兩者有其中一個不是 0 時,width 和 height 值就不會是實際上眼睛所看到的寬、高。

分享到