CSS 背景

CSS background 属性用于为元素的背景添加颜色或图像。例如,

h1 {
    background: orange;
}

浏览器输出

CSS Background Property Description

这里,background 属性为 h1 元素添加了 orange 颜色作为背景。


CSS 背景作为简写属性

有多种 CSS 背景属性可以组合到单个 background 属性中作为简写。background 简写属性的语法是:

background: background-image background-position / background-size background-repeat background-attachment background-origin background-clip background-color;

这里,

注意:简写 background 属性值的顺序推荐按照语法进行。如果省略了任何值,则将采用该属性值的默认值。


示例:CSS 背景简写属性

让我们看一个例子,

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="style.css" />
        <title>CSS background</title>
    </head>

    <body>
        <!-- Adding a background image -->
    </body>

</html>
body {
    /* background shorthand property */
    background: url("avatar.png") top center no-repeat lightgray;
}

浏览器输出

CSS Background Shorthand Property Example

在上面的例子中:

background: url("avatar.png") top center no-repeat lightgray;

等同于:

body {
    background-image: url("avatar.png");
    background-position: top center;
    background-repeat: no-repeat;
    background-color: lightgray;
}

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战