作者:小 琛
欢迎转载,请标明出处
盒子的概念
页面中的每一个标签,都可以看作是一个盒子,通过这个盒子布局。浏览器在渲染网页时,也会将网页中的元素看作一个个矩形——盒子。
例如:CSND主页的上栏。其实就可以看作是一个盒子,盒子内包括了很多内容
盒子的组成
盒子由content内容、border边框线、padding内边距、margin外边距
content内容区域
- 内容区域:一般包括高度、宽度、背景颜色等属性
border边块线
盒子的边框线,一般的,区域和区域间都有边框线,目的是区分块,例如:
语法:border: ?px solid/dashed/dotted color
边框的粗细、类型、颜色
- bd+Tab可以自动生成格式
- 默认情况下,border会将四边均加边框,可以通过border-left/right/top/bottom来自定义某些边
padding内边距
页面间的内容一般情况下是不会和某个块(盒子)定紧紧相挨着的,会留部分空白,例如下图:
语法:padding top left right bottom
设定四个方位的内边距
- 若只给三个值,为top left&right bottom
- 若给两个值,为 top&bottom left&right
margin外边距
一般情况下,为了页面美观,块与块之间会留有距离,例如:
语法:与padding完全相同
语法:margintop left right bottom
设定四个方位的内边距
- 若只给三个值,为top left&right bottom
- 若给两个值,为 top&bottom left&right
一些开发注意事项和技巧
- border、padding和margin的距离均会加在块的总大小内,例如设定了width:400 height:200,而border设定2px,则总width将会为:400+2+2
height为200+2+2
实现自动内减
添加属性:box-sizing:border-box
- 一般的块元素有默认的padding和margin设定,因此在开发中进行修正
清除默认设定
这里采用京东的代码风格:
*{
padding: 0;
border: 0;
box-sizing: border-box;
}
实例
实现如下:
<!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>新浪导航</title>
<style>
.box {
height: 40px;
border-top: 3px solid #ff8500;
border-bottom: 1px solid #edeef0;
background-color: #fcfcfc;
}
.box a {
width: 80px;
height: 40px;
display: inline-block;
text-align: center;
background-color: #edeef0;
line-height: 40px;
color: #4c4c4c;
text-decoration: none;
font-size: 12px;
}
.box a:hover{
background-color: #edeef0;
color: #ff8500;
}
</style>
</head>
<body>
<div class="box">
<a href="">新浪导航</a>
<a href="">新浪导航</a>
<a href="">新浪导航</a>
<a href="">新浪导航</a>
</div>
</body>
</html>
<!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>新闻列表</title>
<style>
*{
padding: 0;
border: 0;
box-sizing: border-box;
}
.news{
width: 500px;
height: 400px;
border: 1px solid #ccc;
margin: 50px auto;
padding: 30px 30px 0;
text-align: center;
}
h1{
font-size: 29px;
line-height: 1;
border-bottom: 1px dashed #000;
padding-bottom: 9px;
}
.news ul {
list-style: none;
}
.news a {
text-decoration: none;
color: #666;
font-size: 18px;
}
.news li{
height: 50px;
line-height: 50px;
border-bottom: 1px dashed #ccc;
padding-left: 28px;
}
</style>
</head>
<body>
<div class="news">
<h1>最新文章/New articles</h1>
<ul>
<li><a href="">背景招聘网页设计,平面设计.php</a></li>
<li><a href="">背景招聘网页设计,平面设计.php</a></li>
<li><a href="">背景招聘网页设计,平面设计.php</a></li>
<li><a href="">背景招聘网页设计,平面设计.php</a></li>
<li><a href="">背景招聘网页设计,平面设计.php</a></li>
</ul>
</div>
</body>
</html>