HTML/CSS 背景图片问题

HTML/CSS background image issues

我目前正在尝试测试如何用图像背景完全覆盖我的 Angular 网页。我在网上研究了很多关于如何实现这一点的例子。这就是我在我的 .html 和 .css 代码中想到的:

<main class="mainPage">
      <router-outlet></router-outlet>
    </main>

html, body{
  height: 100%;
  /*font-family: Arial, Helvetica, sans-serif;*/
  width: 100%;
  margin: 0px;
  padding: 0px;
  border: 0px;
  min-height: 375px;
 }

 .mainPage {
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background: url(/assets/images/background.png) no-repeat center center fixed;
   background-size: cover;
 }

main {
  height: 100%;
  width: 100%;
}

我的印象是,如果您希望图像覆盖屏幕背景,您应该这样定义 CSS。但是,当我 运行 使用 npm start 并遍历到 localhost:4200 时,我看到以下输出:

Background

看起来图片并没有覆盖整个网页,它只覆盖了 HTML 标签中定义的任何内容(例如 Angular 徽标图片)。我的 html 有什么问题吗?还是我在其他地方的 angular 项目中有什么问题?

解决方案: 根据 codechick 的回复,我从 html 和主要 CSS 标签定义中删除了 height/width 属性。相反,我添加了:

.mainPage {
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background: url(/assets/Wood.png) no-repeat center center fixed;
  background-size: cover;
  height: 100vh;
}

好吧,如果你想用背景图片覆盖网页,你需要设置宽度和高度。此外,您的 CSS 中可能有一些语法错误。

.mainPage {
background-image: url("/assets/images/background.png");
background-size: cover;
background-repeat: no-repeat;
width: 100%;
height: 100vh;
background-attachment: fixed;
}

试试这个...希望它有效!

首先您不需要 body, html {height:100%} 然后删除 main 的高度。使用 height: 100vh 作为 .mainPage 或图像容器。

在这里查看我的代码:codepen