盒子模型:
HTML中的每個元素都被視作一個“盒子”,無論它是段落,< div >,還是圖像等。盒子具有一致的屬性,無論我們是否看到它們,也無論是否在樣式表中指定它們,它們總是存在的。
下圖顯示了盒子模型的圖形。盒子模型描述了每個HTML塊級元素對邊框、填充和邊距所具有的潛力,以及如何使用邊框、填充和邊距。
通過上圖描述,概念可能仍很模糊,接下來讓我們用示例來看一下究竟什麼是盒子模型。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>簡單示例</title>
<style>
div#d1{
width: 250px;
height: 100px;
background-color: yellow;
}
div#d2{
width: 250px;
height: 100px;
background-color: darkgreen;
border: 1px solid #000000;
padding: 10px;
margin: 10px;
}
div#d3{
width: 250px;
height: 100px;
background-color: darkgreen;
border: 20px solid #000000;
padding: 30px;
margin: 30px;
}
</style>
</head>
<body>
<div id="d1">DIV #1</div>
<div id="d2">DIV #2</div>
<div id="d3">DIV #3</div>
</body>
</html>
看下效果圖:
比較三個div不同的屬性可以發現,margin設置元素之外的空間,padding設置元素內的空間,border則用於設置元素邊框,倘若不設置則不可見,但事實上其仍然存在!
通過上述實驗,不難得出元素的具體大小:
高度:height+padding-top+padding-bottom+border-top+border-bottm+margin-top+margin-bottm
寬度:width+padding-right+padding-left+border-right+border-left+margin-right+margin-left
定位:
相對定位:
相對於自己原來位置進行定位,且不影響其他元素顯示。如下例所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>歡迎登陸</title>
<style type="text/css">
div{
position: relative;
width: 250px;
height: 100px;
border: 1px solid #000000;
font-weight: bold;
text-align: center;
}
div#d1{
background-color: darkgreen;
}
div#d2{
left: 100px;
background-color: cadetblue;
}
div#d3{
background-color: cornflowerblue;
}
div#d4{
background-color: darkslateblue;
}
</style>
</head>
<body>
<div id="d1">DIV1</div>
<div id="d2">DIV2</div>
<div id="d3">DIV3</div>
<div id="d4">DIV4</div>
</body>
</html>
效果圖:
改變DIV1的相對位置爲:
div#d1{
top: 100px;
background-color: darkgreen;
}
效果圖:
絕對定位:
它能使你設置HTML內容在頁面上的精確位置。即你可以根據設置top\bottom\left\right屬性將元素放在頁面的任意位置。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>絕對定位</title>
<style type="text/css">
div#d1{
position: absolute;
width: 250px;
height: 100px;
left: 100px;
top: 100px;
background-color: darkslateblue;
}
div#d2{
position: absolute;
width: 250px;
height: 100px;
left: 140px;
top: 140px;
background-color: steelblue;
}
div#d3{
position: absolute;
width: 250px;
height: 100px;
left: 180px;
top: 180px;
background-color: green;
}
div#d4{
position: absolute;
width: 250px;
height: 100px;
left: 220px;
top: 220px;
background-color: grey;
}
</style>
</head>
<body>
<div id="d1">DIV#1</div>
<div id="d2">DIV#2</div>
<div id="d3">DIV#3</div>
<div id="d4">DIV#4</div>
</body>
</html>