HTML 和 CSS - 横幅和背景定位

  • 本文关键字:背景 定位 CSS HTML html css
  • 更新时间 :
  • 英文 :


我正在构建一个简单的登录页面,访问者会看到一个横幅,它下面的背景图像和几个垂直位于彼此下方的按钮。

我遇到的问题是,目前,横幅和背景图像都从同一位置(网页的左上角(开始,因此部分背景被横幅隐藏。

我目前拥有的代码是:

<style>
  body {
    background: url("http://url.to/background") no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
    padding: 0px;
    margin: 0px;
  }
  #Wrap {
    position: absolute;
  }
</style>
<body>
  <div id="Wrap">
    <img src="http://url.to/banner" />
  </div>
</body>

预期结果是让横幅图像在适合屏幕的同时占据页面的开头,而不会导致出现任何额外的滚动。更重要的是让背景在横幅之后开始。

可以在以下 URL 中找到小提琴:

https://jsfiddle.net/morL1zka/

任何帮助或想法将不胜感激。

您应该为此使用background-position-y,并且需要设置等于横幅高度

的值

body {
  background: url("https://www.w3schools.com/css/img_fjords.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  padding: 0px;
  margin: 0px; 
  background-position-y: 100px;/*the value must be the same height as the banner */
  
}
#Wrap {
  position: absolute;
}
<div id="Wrap">
  <img src="http://url.to/banner" />
</div>

你可以使用 JavaScript 轻松解决这个问题。背景位置将自动设置在横幅下方,而不知道它的高度。

var body = document.getElementById('body-margin');
var banner = document.getElementById('banner');
body.style.backgroundPositionY = banner.offsetHeight + 'px';
body {
  background: url("http://simonakoleva.me/wp-content/themes/hitchcock/images/bg.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  margin: 0px;
  padding: 0px;
}
#Wrap {
  background-color: #345370;
  text-align:center;
}
<body id="body-margin">
  <div id="Wrap">
    <img id="banner" src="http://simonakoleva.me/wp-content/uploads/2017/05/mybanner.jpg" />
  </div>
</body>

这也是你更新的小提琴:https://jsfiddle.net/morL1zka/2/

最新更新