CSS学习笔记11 CSS背景

background-color:背景色

前面咱们常常用background-color这个属性来设置元素的背景色,例以下面这条css可将段落的背景色设置为灰色css

p {background-color: gray;}

若是想要元素的背景色向外延伸,则只需增长内边距便可html

background-color能够为全部元素设置背景色,这包括 body 一直到 em 和 a 等行内元素。浏览器

注意:background-color 不能继承,其默认值是 transparent。transparent 有“透明”之意。也就是说,若是一个元素没有指定背景色,那么背景就是透明的,这样其祖先元素的背景才能可见。app

 

background-image:背景图像

除了能够为元素设置背景色以外,还能够用background-image属性为元素设置背景图像,其默认值是 none,表示元素背景上没有放置任何图像。ide

若是须要设置一个背景图像,必须为这个属性设置一个 URL 值:url

body {background-image: url(img/a.jpg);}

一般状况下背景应用于 body 元素。spa

注意:同background-color同样,background-image 也不能继承,事实上,全部背景属性都不能继承。背景图片会盖住背景颜色。也就是说背景图片的优先级要高于背景色。3d

 

background-repeat:背景重复

上面中的例子中,咱们看到图片铺满了整个屏幕,若是须要设置是否须要平铺以及平铺的方向,可使用background-repeat属性code

属性值orm

效果

repeat

水平垂直方向上都平铺

repeat-x

水平方向上平铺

repeat-y

垂直方向上平铺

no-repeat

不平铺

 

 

 

 

 

 

 

 

 

background-position:背景定位

默认状况下,背景图片的位置的在元素的左上角,这时能够利用 background-position 属性改变图像在背景中的位置。

 

background-position可能的值

 

background-attachment:背景关联

scroll: 默认值,背景图像会随着页面其他部分的滚动而移动。
fixed:固定显示,相对于body固定。通常只用于body的背景设置。

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>CSS背景</title>
 6     <style type="text/css">
 7         body {
 8             background-image: url(img/a.jpg);
 9             background-repeat: no-repeat;
10             background-attachment: fixed;
11         }
12     </style>
13 </head>
14 <body>
15     <p>图像不会随页面的其他部分滚动。</p>
16     <p>图像不会随页面的其他部分滚动。</p>
17     ...
18     <p>图像不会随页面的其他部分滚动。</p>
19 </body>
20 </html>

 

属性合写

能够将上面讲到的属性用background属性进行合写,一般建议使用这个属性,而不是分别使用单个属性,由于这个属性在较老的浏览器中可以获得更好的支持,并且须要键入的字母也更少。

background合写的顺序: 背景颜色、背景图地址、平铺设置、背景图滚动、背景图位置。如:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>CSS属性合写</title>
 6     <style type="text/css">
 7         body {
 8             background: yellow url(img/a.jpg) no-repeat scroll center top;
 9         }
10     </style>
11 </head>
12 <body>
13     <p>段落1</p>
14     <p>段落2</p>
15     ...
16     <p>段落20</p>
17 </body>
18 </html>

相关文章
相关标签/搜索