概述
网页布局的本质实际上包括三步:
- 1.创建不同的元素(盒子)
- 2.利用css设置盒子的样式
- 3.向盒子里填充不同的内容
因此,想要学会网页布局,首先要了解盒子模型(box model:
盒子模型通常包括以下内容:
- 内容:盒子里真正放置的主体
- 边框
border
:围绕内容的边 - 内边距
padding
:内容到边框之间的距离 - 外边距
margin
:盒子与盒子之间的距离
边框
常用属性:
属性 | 设置内容 | 值 |
---|---|---|
border-width | 边框粗细 | 像素 |
border-style | 边框线型 | solid 实线,dotted 点线,dashed 虚线 |
border-color | 边框颜色 | 颜色值 |
border-top/bottom/left/right | 上下左右 | 复合属性值 |
border | 整体属性 | 复合属性值 |
- 写复合属性时一般按照粗细-线型-颜色写,例如
border: 1px solid red
- 边框会影响盒子的整体大小,准确的说是盒子的整体大小等于盒子内容加上边框的大小,例如:
div { width: 200px; height: 200px; background-color: aquamarine; border: solid red 10px; }
,盒子的整个大小(面积)是220 * 220
内边距
padding-top/bottom/left/right
设置上下左右内边距,单位像素padding
设置复合属性padding: 10px
:上下左右10pxpadding: 1px 10px
:上下1px,左右10pxpadding: 1px 5px 10px
:上1px,左右5px,下10pxpadding: 1px 5px 8px 10px
:上1px,右5px,下8px,左10px(从上开始,顺时针)
- 内边距同样会使得整个盒子变大,例如:
div { width: 200px; height: 200px; background-color: aquamarine; border: solid red 10px; padding: 50px; }
,盒子总面积320 * 320
外边距
margin-top/bottom/left/right
同padding
,例如可设置上下左右外边距margin
设置复合属性margin: 10px
:上下左右10pxmargin: 1px 10px
:上下1px,左右10pxmargin: 1px 5px 10px
:上1px,左右5px,下10pxmargin: 1px 5px 8px 10px
:上1px,右5px,下8px,左10px(从上开始,顺时针)
- 外边距典型应用,将左右外边距设置为
margin: 0 auto;
,使得盒子水平居中;想要实现行内元素水平居中对齐,则可设置父元素text-align: center;
当成文本居中对齐
<style>
div {
width: 200px;
height: 200px;
background-color: orange;
/* 盒子左右外边距设为auto实现水平居中 */
margin: 0 auto;
/* 将行内元素父元素的text-align设置为center实现行内元素水平居中对齐 */
text-align: center;
}
</style>
</head>
<body>
<div>
<span>span</span>
</div>
</body>
- 外边距叠加原则:若两个盒子同时设置公共空间的外边距,例如第一个盒子的下外边距和第二个盒子的上外边距则会出现外边距叠加,垂直方向上,外边距叠加结果取二者中最大的;水平叠加则是二者相加之和
/* 垂直方向上,外边距叠加结果取二者中最大的;水平叠加则是二者相加之和 */
.box1 {
width: 200px;
height: 200px;
background-color: aquamarine;
margin-bottom: 50px;
margin-right: 50px;
}
.box2 {
width: 200px;
height: 200px;
background-color: aquamarine;
margin-top: 100px;
}
.s1 {
background-color: blueviolet;
margin-right: 50px;
}
.s2 {
background-color: blueviolet;
margin-left: 50px;
}
</style>
</head>
<body>
<!-- 垂直方向取最大 -->
<div class="box1"></div>
<div class="box2"></div>
<!-- 水平方向取二者之和 -->
<span class="s1">span1</span>
<span class="s2">span2</span>
</body>
- 父子元素外边距叠加问题
若父子元素同时设置上外边距会使得整个盒子上外边距合并为二者中最大,类似垂直合并,而子元素并不会在父元素中有外边距,想要解决该问题可设置父元素overflow: hidden;
.f {
width: 200px;
height: 200px;
background-color: green;
margin-top: 200px;
/* 为了使得子元素可以按照预想的在父元素中有外边距,可设置父元素overflow: hidden; */
overflow: hidden;
}
/* 父元素上外边距200,子元素上外边距100,整个盒子上外边距为二者最大200 */
.s {
width: 100px;
height: 100px;
background-color: orange;
margin-top: 100px;
}
</style>
<body>
<div class="f">
<div class="s"></div>
</div>
</body>
- 清除默认内外边距
浏览器默认会设置外边距8px,
开发时需要清除这些默认样式:
<style>
* {
margin: 0;
padding: 0;
}
<style>