snøreven snøreven - 2 months ago 9
HTML Question

Match background-image scale-level in header over background-size:cover

I have a two block elements, the first one (

<section>
) being the size of the browser window and rendering a dynamically sized background image (using
background-size: cover;
). The other one a fixed
<header>
with constant height of 62px and a bigger
z-index
.

HTML body:

<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;
}


I want the background image of the
<header>
to have a "scale-factor" equal to that of the
<section>
, but only showing the constant height. That means it should show exactly the first 62 pixel rows that the
<section>
element is rendering, and therefore be invisible to the user (when he is at vertical position 0/hasn't scrolled yet).

Link to a fiddle: https://jsfiddle.net/f1nhum9u/1/

Answer

You can add the fixed behavior for the bg header. With background-attachment:

This keyword means that the background is fixed with regard to the viewport. Even if an element has a scrolling mechanism, a ‘fixed’ background doesn't move with the element.

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>