文章目录
- 背景
- 背景样式和背景图片重复方式
- 1. 背景样式
- 2. 背景图片
- 3. 背景图片的重复方式
- 背景图片的定位
-
- 背景简写
- 1. 分开写背景的各个样式
- 2. 简写 background
背景
背景样式和背景图片重复方式
| <!DOCTYPE html> |
| <html> |
| <head> |
| <meta charset="utf-8" /> |
| <title></title> |
| <style type="text/css"> |
| .box1 { |
| width: 1024px; |
| height: 724px; |
| margin: 0 auto; |
| |
| background-color: #bfa; |
| |
| background-image: url(img/1.png); |
| background-repeat: repeat-y; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="box1"></div> |
| </body> |
| </html> |
复制

1. 背景样式
复制
2. 背景图片
background-image 来设置背景图片
- 语法:background-image:url(相对路径);
- 如果背景图片大于元素,默认会显示图片的左上角
- 如果背景和元素一样大,则会将背景图片全部显示
- 如果背景元素小于元素大小,则会默认将背景图片平铺以充满元素
- 可以同时为一个元素指定背景颜色和背景图片,
- 这样背景样式将会作为背景图片的底色
- 一般情况下设置背景图片时都会同时指定一个颜色
| background-image: url(img/1.png); |
复制
3. 背景图片的重复方式
- background-repeat 用来设置背景图片的重复方式
- 可选值:
- repeat,默认值,背景图片会双重复(平铺)
- no-repeat,背景图片不会重复,有多大就显示多大
- repeat-x,背景图片沿水平方向重复
- repeat-y,背景图片沿垂直方向重复
| background-repeat: repeat-y; |
复制
背景图片的定位
| <!DOCTYPE html> |
| <html> |
| <head> |
| <meta charset="utf-8" /> |
| <title></title> |
| <style type="text/css"> |
| * { |
| margin: 0; |
| padding: 0; |
| } |
| .box1 { |
| height: 500px; |
| margin: 0 auto; |
| |
| |
| |
| background-color: #bfa; |
| |
| |
| |
| background-image: url(img/4.png); |
| |
| |
| |
| background-repeat: no-repeat; |
| |
| background-attachment: fixed; |
| } |
| body { |
| background-image: url(img/3.png); |
| background-repeat: no-repeat; |
| background-attachment: fixed; |
| } |
| </style> |
| </head> |
| <body style="height: 5000px;"> |
| <div class="box1"></div> |
| </body> |
| </html> |
复制

1. 背景的定位
1. 说明
- 背景图片默认贴着元素的左上角显示
- 通过 background-position 可以调整背景图片在元素中的位置
2. 可选值
- 该属性可以使用 top right left bottom center 中的两个值来指定一个背景图片的位置
- top left 左上
- bottom right 右下
- 如果只给出一个值,则第二个值默认是 center
也可以直接指定两个偏移量
-
第一个是水平偏移量
- 如果指定的是一个正值,则图片向右移动指定的像素
- 如果指定的是一个负值,则图片向左移动指定的像素
-
第二个是垂直偏移量
- 如果指定的是一个正值,这图片向下移动指定的像素
- 如果指定的是一个负值,则图片向上移动指定的像素
| background-position: -80px -40px; |
复制
2. 背景图片跟随滚动
-
background-attachment 用来设置背景图片是否随着页面一起滚动
-
可选值: - scroll,默认值,背景图片随着窗口滚动 - fixed,背景图片会固定在某一位置,不随页面滚动
不随窗口滚动的图片,我们一般都设置给 body,而不设置给其他元素
-
当背景图片的 background-attachment 设置为 fixed 时,
| background-attachment: fixed; |
复制

背景简写
| <!DOCTYPE html> |
| <html> |
| <head> |
| <meta charset="utf-8" /> |
| <title></title> |
| <style type="text/css"> |
| body { |
| background-color: #bfa; |
| background: #bfa url(img/3.png) center center no-repeat fixed; |
| } |
| </style> |
| </head> |
| <body></body> |
| </html> |
复制

1. 分开写背景的各个样式
| |
| /background-color: #bfa; |
| |
| background-image: url(img/3.png); |
| |
| background-repeat: no-repeat; |
| |
| background-position: center center; |
| |
| background-attachment: fixed; |
复制
2. 简写 background
- 通过该属性可以同时设置所有相关的样式
- 没有顺序的要求,谁在前谁在后都行
| background: #bfa url(img/3.png) center center no-repeat fixed; |
复制