1、背景颜色
默认为transparent(透明)
(1)将背景设置为greenyellow:
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 200px; height: 150px; background-color: greenyellow; } </style> </head> <body> <div>今天是星期一</div> </body> </html>
2、背景图片
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 200px; height: 150px; background-image: url(img/back.jpg); } </style> </head> <body> <div></div> </body> </html>
3、背景平铺
如果要在html页面上对背景进行平铺,可以使用background-repeat属性,属性的值有:repeat、no-repeat、repeat-x、repeat-y,默认情况下是平铺的
(1)平铺:
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 400px; height: 300px; background-image: url(img/back.jpg); background-repeat: repeat; } </style> </head> <body> <div></div> </body> </html>
(2)延x轴平铺:
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 400px; height: 300px; background-image: url(img/back.jpg); background-repeat: repeat-x; } </style> </head> <body> <div></div> </body> </html>
(3)延y轴平铺:
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 400px; height: 300px; background-image: url(img/back.jpg); background-repeat: repeat-y; } </style> </head> <body> <div></div> </body> </html>
4、背景图片的位置
可以使用方位名词(top、center、bottom、left、center、right,如果是方位名词,两个位置名词不区分先后顺序)或者精确单位
(1)方位名词
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 400px; height: 300px; background-image: url(img/back.jpg); background-repeat: no-repeat; background-position: center top; } </style> </head> <body> <div></div> </body> </html>
(2)精确单位(xy坐标又先后顺序)
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 400px; height: 300px; background-image: url(img/back.jpg); background-repeat: no-repeat; background-position: 25px 40px; } </style> </head> <body> <div></div> </body> </html>
(3)混合单位
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 400px; height: 300px; background-image: url(img/back.jpg); background-repeat: no-repeat; background-position: center 40px; background-color: pink; } </style> </head> <body> <div></div> </body> </html>
5、背景固定
background-attachment:当属性的值定义为scroll的时候背景图片随对象的内容滚动;当定义为fixed的时候,背景图片固定
(1)一般的书写方式
<html> <head> <meta charset="utf-8"> <title></title> <style> body{ width: 400px; height: 1300px; background-image: url(img/back.jpg); background-repeat: repeat; background-position: center 40px; color:red; background-attachment: fixed; } </style> </head> <body> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> <p>下雪了!!!</p> </body> </html>
当滚动鼠标的时候,文字滚动,图片不动
(2)复合性的书写方式:
上面的css代码可以简写为:
<style> body{ width: 400px; height: 1300px; background: url(img/back.jpg) repeat fixed center 40px; color:red; } </style>
没有先后顺序的要求
6、背景颜色半透明
<html> <head> <meta charset="utf-8"> <title></title> <style> div{ width: 200px; height: 300px; background: rgba(0,0,0,0.2); } </style> </head> <body> <div>半透明显示</div> </body> </html>