Cameron W. Cameron W. - 5 months ago 9
jQuery Question

Show nothing but the background image/colour above a fixed element

On our page we have a

position: fixed
header that stays at the top of the page as you scroll. Our product team wishes to have a gap/margin between this fixed element and the top navbar.

However, once we add in this gap, when the user scrolls, they can then see the elements scrolling away above the fixed header. I have created a jsfiddle to show the problem:

https://jsfiddle.net/9n50o567/

If you scroll down, the grey sections appear above the light-blue header while you are scrolling.

Is there anyway to hide this from the user? So all that would show above the fixed element is the background colour, or the background image if there is one (as it will vary from user to user). Essentially masking the elements?

We have tried creating a div that takes on the same colour as the body's background colour, however this just doesn't work when there is a background image. Also we tried using jQuery to detect what elements are present in that section and hiding them as they scroll through, but if the element is bigger than the header, it would dissapear prematurely.

I'm not sure if any of this is making sense, so if you have any more questions, please don't hesitate to ask below.

Answer

This is not perfect, certainly it works for colors, but background-images may be a little harder.

A positioned pseudo-element on the <body> which inherits the body bg color seems to work.

body {
  background: red;
  position: relative;
}
body::before {
  content: '';
  height: 25px;
  display: block;
  width: 100%;
  background: inherit;
  position: fixed;
  top: 0;
  left: 0;
}
.header {
  background-color: #ccffff;
  height: 300px;
  width: 500px;
  border: 1px solid black;
  position: fixed;
  top: 25px;
  left: 8px;
}
.push {
  height: 335px;
}
.section {
  background-color: #cccccc;
  height: 300px;
  width: 500px;
  border: 1px solid black;
  margin-bottom: 15px;
  z-index: 10;
}
<div class="header"></div>

<div class="push"></div>

<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>

JSfiddle Demo

Background image fiddle (with background-attachment:fixed) - Fiddle

Comments