【CSS学习笔记5】-背景

2023-09-21  本文已影响0人  兔小小

背景颜色 background-color

body {
  background-color: lightblue;
}
h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

p {
  background-color: yellow;
}

其他表示颜色的值

不透明度

div {
  background-color: green;
  opacity: 0.3;
}

RGBA

div {
  background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */
}

背景图片 background-image

body {
  background-image: url("paper.gif");
}
body {
  background-image: url("bgdesert.jpg");
}

特定元素的背景图片:

p {
  background-image: url("paper.gif");
}

背景重复 background-repeat

默认情况下,该属性在水平和垂直方向上重复图像。

body {
  background-image: url("gradient_bg.png");
}

如果上图仅水平重复(),背景将看起来更好background-repeat: repeat-x;

body {
  background-image: url("gradient_bg.png");
  background-repeat: repeat-x;
}

没有重复:background-repeat: no-repeat;

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
}

背景位置 background-position

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
}

绑定 attachment

滚动图片不动:

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  background-attachment: fixed;
}

指定背景图像应与页面的其余部分一起滚动:

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  background-attachment: scroll;
}

缩短代码 background

这个代码还是比较长的

body {
  background-color: #ffffff;
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
}

您可以使用速记属性:background,缩短代码可以有一样的效果

body {
  background: #ffffff url("img_tree.png") no-repeat right top;
}

使用这个属性时要记得属性值的顺序为:

缺少其中一个属性值并不重要,只要其他的按此顺序排列。请注意,在上面的示例中,我们不使用 background-attachment 属性,因为它没有值。

上一篇 下一篇

猜你喜欢

热点阅读