Skip to content

CSS 背景

背景是网页设计中一个非常重要的视觉元素。CSS 提供了丰富的属性来控制元素的背景,包括颜色、图片、位置、大小等。

background-color

background-color 属性用于设置元素的背景颜色。

css
body {
  background-color: lightblue;
}

h1 {
  background-color: #ffffff; /* 使用十六进制颜色值 */
}

div {
  background-color: rgb(255, 255, 204); /* 使用 RGB 值 */
}

background-image

background-image 属性用于将一张图片设置为元素的背景。

css
body {
  background-image: url('paper.gif');
}

默认情况下,背景图片会在水平和垂直方向上重复平铺,以覆盖整个元素。

background-repeat

background-repeat 属性控制背景图片的平铺方式。

  • repeat: (默认) 水平和垂直方向都平铺。
  • repeat-x: 只在水平方向上平铺。
  • repeat-y: 只在垂直方向上平铺。
  • no-repeat: 不平铺,图片只显示一次。
css
body {
  background-image: url('gradient_bg.png');
  background-repeat: repeat-x;
}

background-position

background-position 属性用于设置背景图片在元素内的起始位置。你可以使用关键字(如 top, bottom, left, right, center)或具体的坐标值。

css
body {
  background-image: url('tree.png');
  background-repeat: no-repeat;
  background-position: right top; /* 将图片定位到右上角 */
}

div {
    background-image: url('flower.png');
    background-repeat: no-repeat;
    background-position: 50% 50%; /* 效果同 center center */
}

background-attachment

background-attachment 属性决定背景图片是随着页面的其余部分滚动,还是固定在视口上。

  • scroll: (默认) 背景图片会随着页面的滚动而移动。
  • fixed: 背景图片会固定在视口上,不随页面滚动。这常用于创建视差效果。
css
body {
  background-image: url('landscape.jpg');
  background-attachment: fixed;
}

background (简写属性)

为了简化代码,你可以使用 background 简写属性,将以上所有背景相关的属性值写在一个声明里。顺序通常是:

background: color image repeat attachment position;

css
body {
  background: #ffffff url('tree.png') no-repeat right top;
}

即使某个属性不需要设置,也建议使用这个简写属性,只需省略该值即可。例如,如果不需要设置 background-attachment,可以不写。

CSS3 背景属性

CSS3 引入了更多强大的背景属性:

  • background-size: 控制背景图片的尺寸。cover 会缩放图片以完全覆盖元素,contain 会缩放图片以完全容纳在元素内。
  • background-origin: 指定 background-position 的参考原点(是基于内容、内边距还是边框)。
  • background-clip: 指定背景的绘制区域(是延伸到边框、内边距还是只在内容区域)。
  • 多重背景: 你可以为一个元素设置多个背景图片,用逗号隔开。
css
#example1 {
  background-image: url(flower.gif), url(paper.gif);
  background-position: right bottom, left top;
  background-repeat: no-repeat, repeat;
  background-size: 50px, 100%;
}

通过组合运用这些背景属性,你可以创造出丰富多彩、富有层次感的视觉设计。

本站内容仅供学习和研究使用。