文章目录
前言
在使用CSS进行网页布局时,我们都要使用到CSS盒子模型,盒子主要是用来装HTML元素的内容。通过盒子模型我们可以更好的进行布局。
一、盒子模型概念
CSS中规定每个盒子分别为:内容区域(content)、内边距区域(padding)、外边距区域(margin)、边框区域(border),这四个部分就构成了完整的CSS盒子模型。
二、盒子模型的构成
1.内容区(content)
- 内容区是整个盒子模型的中心,其中存放了网页的主要元素,元素可以是文本 、 图像等。
- 内容区有 width 、 height 、 overflow 三个属性。其中 width 和 height 属性用来指定盒子内容区域的宽度和高度。
代码如下:
div{
background-color: black;
width: auto;
height: 50px;
}
- overflow 属性设置溢出内容的处理方式overflow属性的四个可选值:
属性值 功能 hidden 隐藏溢出的部分 visible 显示溢出的部分,显示在盒子的外面 acroll 添加滚动条 auto 浏览器自动决定如何处置溢出的部分 div{ background-color: aquamarine; width: 300px; height: 300px; padding-left: 50px ; overflow: scroll; }
图例:
2.内边距(padding)
内边距是内容区和边框之间的空间,我们可以通过 padding-top 、 padding-right 、 pa
dding-bottom 、 padding-left 及它们的简写属性 padding 来设置内容区各个方向上与边框之
间的距离。在为盒子模型设置背景属性时,背景属性可以覆盖到内边距区域。
.big{
/* width: auto; */
height: 300px;
background-color: rgb(31, 56, 213);
padding-top: 10px;
padding-bottom:10px;
padding-left:10px;
padding-right:10px
}
- padding-top 设置上边距
- padding-bottom 设置下边距
- padding-right 设置左边距
- padding-left 设置右边距
- 内边距的设置可以padding属性直接设置:
/*内边距 设置四个值:上 右 下 左 */ /* padding :10px 20px 30px 40px */ /* 内边距 设置两个值:上下 左右 */ /* padding:10px 20px; */
3.外边距(margin)
外边距位于盒子模型的最外围,是边框之外的空间。我们通常使用 margin-top 、 margin-b
ottom 、 margin-left 、margin-right 及它们的简写属性 margin 来设置外边距,即控制盒
子和盒子之间的距离。
div{
width: 300px;
height: 300px;
background-color: coral;
margin: 30px 20px;
margin-top:10px;
margin-bottom:10px;
margin-left:10px;
margin-right:10px;
}
- margin-top 设置上边距
- margin-bottom 设置下边距
- margin-right 设置左边距
- margin-left 设置右边距
- 内边距的设置可以margin属性直接设置:
/* 外边距 设置四个值:上 右 下 左 */ /* margin :10px 20px 30px 40px */ /* 外边距 设置两个值:上下 左右 */ /* margin:10px 20px; */
4.边框(border)
边框是环绕内容区和内边距的边界,我们可以使用 border-style 、 border-width 和 bo
rder-color 及它们的简写属性 border 来设置边框的样式。其中, border-style 属性是边框中
最主要的属性。
.one{
background-color: bisque;
width: 300px;
height: 200px;
/* 设置上边框 dashed 虚线 */
border-top-style: dashed;
border-top-color: aqua;
border-top-width: 5px;
/* 设置下边框 dotted 小圆点 */
border-bottom-style: dotted;
border-bottom-color: blue;
border-bottom-width: 5px;
/* 设置左边框 double 双实线 */
border-left-style: double;
border-left-color: blueviolet;
border-left-width: 5px;
/* 设置右边框 solid 实线 */
border-right-style: solid;
border-right-color: yellow;
border-right-width: 5px;
}
.two{
background-color: aquamarine;
width: 400px;
height: 300px;
/* 统一设置边框: 宽度 类型 颜色 */
border: 5px solid red;
}
4.1 (边框样式)border-style
主要设置边框的样式,主要有以下样式:
属性值 | 说明 |
none | 无边框 |
soild | 实线边框 |
dashed | 虚线边框 |
dotted | 点状边框 |
double | 双实线边框 |
hidden | 隐藏,与none功能一样 |
图例:
4.2 (边框宽度)border-width
设置边框宽度,主要有以下属性:
属性 | 说明 |
thin | 较细的边框 |
medium | 中等宽度的边框 |
thick | 较粗的边框 |
length | 可以用单位为px表示,自己设置宽度 |
4.3 (边框颜色)border-color
设置边框的颜色,颜色的表示方式主要有三种:
表示方式 | 例子 |
直接颜色的英文表示 | border-color:red; |
十六进制表示 | border-color:#FF0000; |
rgb函数表示 | border-color:rgb(255,255,0); |
总结
以上就是今天要介绍的内容,主要内容为盒子模型以及盒子模型的各个属性,希望对大家有所帮助。