碎碎念:知识点梳理归纳,如果有什么不对的感谢大家指正一起学习!
1. background-size
- 设置背景图片大小(图片可以保其原有尺寸)
- 第一个值为图片宽度,第二个值为高度(只写一个值另外一个默认为auto)
语法:
background-size: length || percentage || cover || contain;
属性 | 功能 |
---|---|
length | 设置背景图片高度和宽度。第一个值设置宽度,第二个值设置的高度。如果只给出一个值,第二个是设置为 auto(自动) |
percentage | 将计算相对于背景定位区域的百分比。第一个值设置宽度,第二个值设置的高度。如果只给出一个值,第二个是设置为"auto(自动)" |
cover | 缩放背景图片以完全覆盖背景区,可能背景图片部分看不见。和 contain 值相反,cover 值尽可能大的缩放背景图像并保持图像的宽高比例(图像不会被压扁)。该背景图以它的全部宽或者高覆盖所在容器。当容器和背景图大小不同时,背景图的 左/右 或者 上/下 部分会被裁剪 |
contain | 缩放背景图片以完全装入背景区,可能背景区部分空白。contain 尽可能的缩放背景并保持图像的宽高比例(图像不会被压缩)。该背景图会填充所在的容器。当背景图和容器的大小的不同时,容器的空白区域(上/下或者左/右)会显示由 background-color 设置的背景颜色 |
1.1 150px 150px(length)
宽度和高度都设置为150px
background-size: 150px 150px;
1.2 百分比(percentage )
1.2.1 100% 100%
- 背景图片将铺满整个内容区,背景图片铺满整个外层元素固定区域内
background-size: 100% 100%;
1.2.2 50% auto
宽度为容器的50%,高度自适应
background-size: 50% auto;
1.3 cover/contain
- cover:图片最小的轴覆盖全容器
- contain: 图片最长的轴覆盖全容器
background-size: cover;
background-size: contain;
1.4 auto
- 等同于 auto auto
- 默认值
- 等同于原图片尺寸
background-size: auto;
2.3 background-position
- 背景图位置
/* 第一张图片位置,第二张图片位置 */
background-position: -20px 0px,200px 160px;
2. background-attachment
- 背景图像是否固定或者随着页面的其余部分滚动。
语法: background-attachment:scroll || fixed || inherit
值 | 描述 |
---|---|
scroll | 默认值。背景图像会随着页面其余部分的滚动而移动。 即背景和内容绑定。 |
fixed | 当页面的其余部分滚动时,背景图像不会移动。背景图相对于视口固定。 |
local | 背景图相对于元素内容固定。 |
inherit | 规定应该从父元素继承 background-attachment 属性的设置。 |
2.1 fixed 固定的背景图像,不跟随页面滚动
body {
/* 设置body背景图片 */
background: url(test.png);
background-repeat: no-repeat;
background-attachment: fixed;
}
.box{
/* 文字区域 */
width: max-content;
background-color: pink;
margin-left: 20px;
color: #000;
}
2.2 scroll 背景图像跟随页面滚动,内容动时背景图也动
.box{
background: url(test.jpg);
width: 400px;
height: 350px;
background-repeat: no-repeat;
background-attachment: fixed;
color: #fff;
}
2.2.1 overflow:scroll 影响 attachment:scroll
- 设置scroll属性后,背景图会跟随内容滚动,但是有特殊情况。
- 当元素被设置为可滚动时(overflow:scroll),attachment也设置为scroll时,背景图不会随着元素滚动而滚动
.box{
background: url(test.jpg);
width: 400px;
height: 350px;
/* 元素滚动 */
overflow: scroll;
background-repeat: no-repeat;
/* 背景图滚动 */
background-attachment: scroll;
color: #fff;
}
2.3 local 滚动元素背景图滚动
- 对于可以滚动的元素(设置为overflow:scroll的元素),设置attachment:local,背景会随着内容滚动而滚动
.box{
background: url(test.jpg);
width: 400px;
height: 350px;
/* 元素滚动 */
overflow: scroll;
background-repeat: no-repeat;
/* 背景固定 */
background-attachment: local;
color: #fff;
}
2.4 attachment多重背景
.box{
width: 100%;
height: 100%;
/* 设置两张背景图 */
background: url(香瓜.jpg), url(噘嘴.jpg);
background-repeat: no-repeat;
/* 设置背景图为滚动,固定 */
background-attachment: scroll, fixed;
color: #fff;
background-size: 300px 300px, 100% 100%;
}