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>
看下效果图:
高度: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>
效果图:
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>
因篇幅问题不能全部显示,请点此查看更多更全内容