我們如果以面向對象的角度去考慮CSS提供的盒子模型,可以建立一個BOX對象進行表示:
public class Box{
// 外邊距:控制與父級元素的距離
public Margin margin;
// 邊框:控制邊框的樣式
public Border border;
// 內邊距:控制元素與邊框之間的距離(又稱之爲填充)
public Padding pad;
// 元素內容:顯示的文字內容
public Content con;
}
如下圖所示
<html>
<head>
<title>CSS盒子模型</title>
<style type="text/css">
div{
/*設置元素部分的寬高*/
width:100px;
height: 100px;
/*設置邊框*/
border-style:solid;
border-color: #22DDDD;
border-width:5px;
/*設置該樣式後,元素外框變大了*/
padding-left: 20px;
padding-top: 50px;
/*設置外邊距*/
margin-left:50px;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="ele" style="background-color: #66ffff">
元素內容
</div>
</body>
</html>
效果圖如下:
盒子正如其名,想象一下我們收到的快遞包裹,在買的物品<content>外面有一個盒子,盒子與物品直接有填充物<padding>防止物品損壞,盒子本身具有一定的厚度和高度<border>,而假設盒子被放在箱子(或任何容器,只要方便理解)中,箱子與盒子之間的距離就是外邊距<margin>。
我們知道,在平面顯示中,需要確定上下左右的距離才能進行定位,在CSS中,定位也是一樣的操作,如果同樣使用面向對象進行理解,可以有如下對象:
public class Margin{
public String top;//上:表示爲margin-top
public String bottom;//下:表示爲margin-bottom
public String left;//左:表示爲margin-left
public String right;//右:表示爲margin-right
}
外邊距有上下左右四個屬性,用來對元素進行定位以及分別設置不一樣的樣式,舉個栗子:border-style:dotted solid double dashed
其代表的順序是邊框的上、右、下、左分別不同的樣式設置。
CSS盒子模型標準分IE版和W3C版,一般都會選擇W3C版作爲顯示標準,當然,如果不加以規定的話,在不同瀏覽器上顯示效果可能有比較大的差異,瀏覽器的默認解析標準並不相同,所以一般會加上doctype 聲明,告訴瀏覽器使用什麼標準進行解析:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
最後,希望本文能幫助到有需要的朋友