盒子的使用
CSS 盒子模型本质上是一个盒子,封装周围的 HTML 元素,它包括:边框、外边距、 内边距、和 实际内容
边框
1. 边框 :边框粗细 || 边框样式 || 边框颜色
border : border-width || border-style || border-color;
2. 上边框 border-top:
下边框 border-bottom
左右同理 border-left
border-right
3. 边框样式 border-style
属性 none:没有边框即忽略所有边框的宽度(默认值)
solid:边框为单实线(最为常用的)
dashed:边框为虚线
合并边框
border-collapse: collapse; 表示相邻边框合并在一起
注意:边框会额外增加盒子的实际大小
内边距
Padding 内边距,边框与内容之间的距离。
Padding: 后直接加距离值
- 合着写:
一个值是代表上下左右都有相同内边距
四个值依此代表上下左右内边距,位置固定,需要几个写几
2. 分着写
上内边距 padding-top:
下内边距 padding -bottom
左右同理 padding-left
padding-right
注意:内边距会影响盒子实际大小
如果盒子已经有了宽度和高度,此时再指定内边框,会撑大盒子。
如何盒子本身没有指定 width/height 属性, 则此时 padding 不会撑开盒子大小。
外边距
margin 属性用于设置外边距,即控制盒子和盒子之间的距离。同内边距
外边距块级盒子水平居中
满足以下两个条件时,可以以让块级盒子水平居中
• 盒子必须指定了宽度(width)。
• 盒子左右的外边距都设置为 auto 。
写法:margin-left: auto;
margin-right: auto;
margin: auto;
margin: 0 auto
外边距合并
- 相邻块元素垂直外边距的合并 当上下相邻的两个块元素(兄弟关系)相遇时,如果上面的元素有下外边距 marginbottom,下面的元素有上外边距 margin-top ,则他们之间的垂直间距不是 marginbottom 与 margin-top 之和。取两个值中的较大者这种现象被称为相邻块元素垂直外边距 的合并。
- 嵌套块元素垂直外边距的塌陷 对于两个嵌套关系(父子关系)的块元素,父元素有上外边距同时子元素也有上外边 距,此时父元素会塌陷较大的外边距值
- 解决方案:为父元素定义上边框或内边距,也可以为父元素添加 overflow:hidden。
清除内外边距
格式
* {
padding:0;/* 清除内边距 */
margin:0;/* 清除外边距 */
}
css新增样式
属性 含义 属性值 继承
background-clip 设置背景覆盖范围 border-box/padding-box/content-box 否
background-origin 设置背景覆盖的起点 border-box/padding-box/content-box 否
background-size 设置背景的大小 conver/contain/长度/百分比 是
border-box: 背景显示区域到边框,默认值
padding-box: 背景显示区域到内边距框
content-box: 背景显示区域到内容
圆角边框
border-radius:length;
可以跟四个值,分别代表左上角、右上角、右下角、左下角
分开写: border-top-left-radius、
border-top-right-radius、
border-bottom-right-radius
border-bottom-left-radius
eg:
<style>
div{
width: 100px;height:100px;
border-width: 5px;
margin-top: 10px;
border-radius:10px;
background-color: pink;
}
.a{
width: 200px;height: 200px;
border-radius: 100px;
}
div .b {
width: 100px;height: 50px;
border-top-left-radius: 20px;
}
.c{
border-radius: 50px;
width: 300px;
}
</style>
<body>
<div class="b"></div>
<div class="c"></div>
<div class="a"></div>
</body>
</html>
效果如下:
盒子阴影
box-shadow 属性为盒子添加阴影
box-shadow: h-shadow v-shadow blur spread color inset;
属性值:
h-shadow 必需。水平阴影的位置。允许负值。
v-shadow 必需。水平阴影的位置。允许负值。
Blur 可选。模糊距离。
Spread 可选。阴影的尺寸
Color 可选。阴影的颜色。请参阅 CSS 颜色值。
Inset 可选。将外部阴影(outset) 改为内部阴影。
eg:
<style>
div{
width: 100px;height:100px;
border-width: 5px;
margin-top: 10px;
border-radius:10px;
background-color: pink;
}
.a{
width: 200px;height: 200px;
border-radius: 100px;
box-shadow: 10px 10px 10px;
}
</style>
<body>
<div class="a"></div>
文字阴影
text-shadow: h-shadow v-shadow blur color;
h-shadow 必需。水平阴影的位置。允许负值。
v-shadow 必需。水平阴影的位置。允许负值。
Blur 可选。模糊距离。
Spread 可选。阴影的尺寸
结尾
赞