在背景大小的标题中匹配背景图像缩放级别:封面

时间:2016-09-30 18:45:09

标签: html css css3

我有两个块元素,第一个元素(<section>)是浏览器窗口的大小,并呈现动态大小的背景图像(使用background-size: cover;)。另一个是固定<header>,常数高度为62px,z-index更高。

HTML正文:

<header></header>
<section></section>

CSS:

html, body {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
}
header {
    position: fixed;
    z-index: 100;
    height: 62px;
    width: 100%;
    background-image: url(image.jpg);
    background-repeat: no-repeat;
    background-position: top center;
    background-size: cover;
 }
section {
    height: 100%;
    width: 100%;
    background-image: url(image.jpg);
    background-repeat: no-repeat;
    background-position: top center;
    background-size: cover;
}

我希望<header>的背景图片具有&#34;比例因子&#34;等于<section>的值,但只显示恒定的高度。这意味着它应该准确显示<section>元素正在渲染的前62个像素行,因此对用户不可见(当他处于垂直位置0 /还没有滚动时)。

链接到小提琴:https://jsfiddle.net/f1nhum9u/1/

1 个答案:

答案 0 :(得分:1)

您可以为bg标头添加fixed行为。使用背景附件:

  

此关键字表示背景是针对视口修复的。即使元素具有滚动机制,“固定”背景也不随元素移动。

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}
header {
  position: fixed;
  z-index: 100;
  height: 62px;
  width: 100%;
  background-image: url(http://www.nasa.gov/images/content/696289main_O_Star_Binary.jpg);
  background-repeat: no-repeat;
  background-position: top center;
  background-size: cover;
  /*ADD THIS*/
  background-attachment: fixed;
}
section {
  height: 100%;
  width: 100%;
  background-image: url(http://www.nasa.gov/images/content/696289main_O_Star_Binary.jpg);
  background-repeat: no-repeat;
  background-position: top center;
  background-size: cover;
}
<header></header>
<section></section>
<br><br><br><br>