如何使用 CSS 添加背景图像

让我们演示如何使用 CSS 样式在 HTML 文档中添加和定位背景图像。

如何定位背景图像。

  • background-image:为元素定义一张或者多张背景图片。
  • background-repeat:指定背景图像是否/如何重复。
  • background-attachment:定义背景图像是随着页面的其余部分滚动还是固定的。
  • background-position:定义背景图片的起始位置。

添加背景图像的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        background-image: url('https://www.onitroad.com/bg.png');
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-position: center;
      }
    </style>
  </head>
  <body>
  </body>
</html>

在上面的示例中,背景图像位于中心(我们也可以使用其他值,例如左上;左中;左下;右上;右中;右下;等等)。

以下是定位背景图像的一些方法:

  • 重复(垂直或者水平)
  • 不重复
  • 完整页面

要重复背景图像,我们可以使用以下值:

  • repeat,垂直和水平重复背景图像,
  • repeat-x,仅水平重复背景图像,
  • repeat-y,仅垂直重复背景图像。

添加垂直重复的背景图像的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        background-image: url("https://www.onitroad.com/onitroad-logo.jpeg");
        background-repeat: repeat-y;
      }
    </style>
  </head>
  <body>
  </body>
</html>

在上面的示例中,背景图像仅垂直重复。

使用“no-repeat”值,这样背景图像就不会重复(图像只会显示一次)。

添加非重复背景图像的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        background-image: url("https://www.onitroad.com/onitroad-logo.jpeg");
        background-repeat: no-repeat;
      }
    </style>
  </head>
  <body>
  </body>
</html>

CSS3 引入了 background-size 属性,它帮助我们控制在其父元素中显示的背景图像大小。

在下面的例子中,作为背景大小的值,我们使用“cover”,它尽可能地缩放背景图像,使背景图像完全覆盖整个区域。

要创建整页背景图像,还要向容器添加一个高度设置为 100% 的背景图像。

添加整页背景图片的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body,
      html {
        height: 100%;
        margin: 0;
      }
      .bg {
        background-image: url("https://www.onitroad.com/onitroad-logo.jpeg");
        height: 100%;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
      }
    </style>
  </head>
  <body>
    <div class="bg"></div>
  </body>
</html>

要添加透明背景图像,我们需要 opacity 属性,该属性指定元素的透明度。

取一个 0.0-1.0 的值。
降低透明度(例如,0.2 表示模糊,0.5 表示半透明)。

添加具有指定不透明度的背景图像的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      img {
        opacity: 0.5;
      }
    </style>
  </head>
  <body>
    <img src="https://www.onitroad.com/onitroad-logo.jpeg" width="300" height="150" alt="onitroad">
  </body>
</html>

在上面的示例中,图像的不透明度为 50%。

日期:2020-06-02 22:14:54 来源:oir作者:oir