
CSS 背景
在网页设计里,CSS 背景属性用于定义元素的背景效果,让网页呈现出更加丰富多样的视觉效果。
在本章节中,你将学习如下 CSS 背景属性:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
CSS 背景颜色
background-color
属性指定元素的背景色,语法结构:background-color:#0000ff;
。
在下面的实例中,通过使用background-color
属性,为body
添加背景颜色:
body {background-color:#b0c4de;}
你可以使用不同的颜色值类定义 CSS 背景颜色,在CSS 颜色中已经讲述了如何指定元素的颜色。
在下面的实例中,通过使用background-color
属性,为h1
、p
和div
添加了不同的背景颜色:
h1 {background-color:#f00;}
p {background-color:#00f;}
div {background-color:#0f0;}
CSS 背景图像
background-image
属性指定元的素背景图像,语法结构:background-image:url('square.jpg');
。
在下面的实例中,通过使用background-image
属性,来设定背景图像:
body {background-image:url('square.jpg');}
在默认状态下,背景图像会以平铺重复的方式呈现,从而将整个元素的实体区域完全覆盖。
CSS 背景图像 - 水平或垂直平铺或去除平铺
background-repeat
属性指定元素的背景图像显示方式,语法结构:background-repeat:no-repeat;
。
1. 在下面的实例中,通过使用background-repeat
属性,为背景图像添加水平平铺效果:
body {background-image:url('square.jpg');}
background-repeat:repeat-x;
2. 在下面的实例中,通过使用background-repeat
属性,为背景图像添加垂直平铺效果:
body {background-image:url('square.jpg');}
background-repeat:repeat-y;
3. 在下面的实例中,通过使用background-repeat
属性,来去除背景图像的平铺效果:
body{
background-image:url('square.jpg');
background-repeat:no-repeat;
}
CSS 背景附着
background-attachment
属性指定元素的背景图像滚动还是固定,语法结构:background-attachment:fixed;
。
在下面的实例中,通过使用background-attachment
属性,来固定背景图像(让背景图像不跟随页面一起滚动):
body{
background-image:url('./square.jpg');
background-repeat:no-repeat;
background-attachment:fixed;
}
CSS 背景图像 - 设置定位
background-position
属性指定元素的背景图像显示位置,语法结构:background-position:right top;
。
在下面的实例中,通过使用background-position
属性,来改变背景图像的位置:
body{
background-image:url('square.jpg');
background-repeat:no-repeat;
background-position:right top;
}
CSS 背景简写
在上面的实例中,我们会看到页面的背景颜色、背景图像、背景平铺、背景附着、背景位置等属性,都需要单独设置。
为了简化这些属性的代码,我们可以将这些属性合并在同一个属性中。
在下面的实例中,通过使用background
属性,来简化背景属性:
body {background:#ffffff url('square.jpg') no-repeat right top;}
当使用简写属性时,属性值的顺序为:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
以上属性无需全部使用,你可以按照页面的实际需要使用。
CSS 背景属性列表
属性 | 描述 |
---|---|
background | 简写属性,作用是将背景属性设置在一个声明中。 |
background-attachment | 背景图像是否固定或者随着页面的其余部分滚动。 |
background-color | 设置元素的背景颜色。 |
background-image | 把图像设置为背景。 |
background-position | 设置背景图像的起始位置。 |
background-repeat | 设置背景图像是否及如何重复。 |
反馈提交成功
感谢您的反馈,我们将尽快处理您的反馈