跳至主要內容

背景样式


背景样式

background-color

background-color 属性可以给指定标签元素设置背景色。

background-image

在 CSS3 中,background-image 属性的属性值可以包含多个图片的地址。语法如下:

/*图片地址*/
background-image: url(), url(), ..., url();

若想让图片放在我们想要的位置,可以使用 background-position 属性设置图片显示的位置。语法如下:

/*图片显示的位置*/
background-position: position1, position2, ..., positionN;

若想要设置图片是否重复显示在页面上,我们可以添加 background-repeat 属性。语法如下:

/*图片是否重复*/
background-repeat: repeat1, repeat2, ..., repeatN;
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #content1 {
        /*小图片来自 icons*/
        background-image: url("icons8-rat-96.png"), url("nemuel.jpg");
        background-position: right bottom, left top; /*相对于父元素大小,老鼠图片右下角显示,大背景图片在左上角显示*/
        background-repeat: no-repeat, no-repeat; /*两张图片不重复*/
        padding: 15px;
        width: 400px;
        height: 260px;
      }
    </style>
  </head>
  <body>
    <div id="content1"></div>
  </body>
</html>
image.png
image.png

background-size

background-image 属性可以把图像插入背景。
background-size 属性可以给背景图设置大小。

属性可以用来控制背景图像的显示大小。语法如下

background-size: length|percentage|cover|contain;
描述
length设置背景图片高度和宽度。第一个值设置宽度,第二个值设置高度。如果只给出一个值,第二个是设置为 auto(自动)。
percentage将计算相对于背景定位区域的百分比。第一个值设置宽度,第二个值设置高度。如果只给出一个值,第二个是设置为"auto(自动)" 。
cover此时会保持图像的纵横比并将图像缩放成将完全覆盖背景定位区域的最小大小。
contain此时会保持图像的纵横比并将图像缩放成将适合背景定位区域的最大大小。

background-position

通过 background-position 属性,可以改变图像在背景中的位置。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        background-image: url("moon.jpg");
        background-size: 300px 300px;
        background-position: center;
      }
    </style>
  </head>
  <body></body>
</html>

background-repeat

background-repeat 属性是用来设置背景图像是否平铺。