CSS3 background 背景图片

662 阅读1分钟
<!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>
    .box {
      width: 500px;
      height: 500px;
      border: 1px solid #000;
      margin: 100px auto;

      /* 背景图片 */
      background: url(temp.png) no-repeat;

      /* 控制背景图片大小 */

      /* 具体数值 */
      /* background-size: 500px 500px; */

      /* 百分比 */
      /* background-size: 50% 50%; */

      /* cover 覆盖,保证完全覆盖盒子,但不能保证完整显示 */
      background-size: cover;

      /* contain 包含, 保证背景图片最大化的在盒子中等比例显示,但不能保证铺满盒子*/
      background-size: contain;
    }
  </style>
</head>
<body>
  <div class="box">

  </div>
</body>
</html>

  • 全屏背景
<!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>
    html, body {
      height: 100%;
    }
    body {
      /* 添加背景图片 */
      background: url(temp1.png) no-repeat center;
      /* 如果还需要添加背景颜色可以在后面直接添加颜色 */
      /* background: url(temp1.png) no-repeat center red; */

      /* 图片会被压缩或者拉伸 */
      /* background-size: 100% 100%; */
      background-size: cover;

      /* 背景原点 控制背景从什么地方开始显示 */
      /* 系统默认值 */
      /* background-origin: padding-box; */
      /* 从 border-box 开始显示 */
      /* background-origin: border-box; */
      /* 从 content-box 开始显示 */
      background-origin: content-box;

      /* 背景裁剪 */
      /* padding-box border-box content-box */
      background-clip: border-box;

      /* 给盒子加多个背景,安卓背景语法格式书写,多个背景使用逗号隔开 */
      /* background: url(temp1.png) no-repeat left top,
                  url(temp1.png) no-repeat right top,
                  url(temp1.png) no-repeat right bottom,
                  url(temp1.png) no-repeat left bottom,
                  url(temp1.png) no-repeat center; */
    }
  </style>
</head>
<body>
  
</body>
</html>