Hide content if under transparent header

Viewed 132

I have a transparent header which can't be a image or a color, it needs to be transparent. Whenever some divs slides under my header I want to hide only the part which is below it.

Problem

body {
  margin: 0;
  width: 100%;
  background-color: yellow;
  height: 100vh;
}

.header {
  height: 5rem;
  top: 0;
  position: fixed;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.content {
  margin-top: 25rem;
  height: 200px;
  background-color: blue;
  color: white;
}

.footer {
  margin-top: 30rem;
  height: 5rem;
  bottom: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
 }
<div class="header"> Header</div>

<div class="content">  DONT SHOW THIS DIV UNDER HEADER</div>

<div class="footer">footer</div>

1 Answers

Actually you can achieve this without javascript at all. You can put element "under" the .header with body's background, and set the proper z-index in order to keep it under.

Something like that:

body {
  margin: 0;
  width: 100%;
  background-color: yellow;
  height: 100vh;
}

.header {
  height: 5rem;
  top: 0;
  position: fixed;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
z-index: 3;
}

.content {
  margin-top: 25rem;
  height: 200px;
  background-color: blue;
  color: white;
z-index: 1;
}

.footer {
  margin-top: 30rem;
  height: 5rem;
  bottom: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
 }
/* this will act as a mask to hide the content when it get "under" the header: */
#contentMask {background: inherit; z-index: 2; position: fixed; top: 0; left: 0; height: 5em; width: 100%;}
<div class="header"> Header</div>
<div class="content">  DONT SHOW THIS DIV UNDER HEADER</div>
<div id="contentMask"></div>
<div class="footer">footer</div>

Edit (as for comment):

You can play with z-index property in order to achieve it. This is a general example:

body {
  margin: 0;
  width: 100%;
  background-color: yellow;
  height: 100vh;
}
.header {
  height: 5rem;
  top: 0;
  position: fixed;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 4;
}
#contentMask {
  background: inherit; 
  position: fixed; 
  top: 0; 
  left: 0; 
  height: 5em; 
  width: 100%;
  z-index: 2;   
}
.content {
  position: relative;
  margin-top: 25rem;
  height: 200px;
  background-color: blue;
  color: white;
  z-index: 1;
}
.under { z-index: 3; }
.above { z-index: 5; }
.footer {
  margin-top: 30rem;
  height: 5rem;
  bottom: 0;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}
<div class="header"> Header</div>
<div id="contentMask"></div>
<div class="content">  DONT SHOW THIS DIV UNDER HEADER</div>
<div class="content under">  SHOW THIS DIV UNDER HEADER</div>
<div class="content above">  SHOW THIS DIV ABOVE HEADER</div>
<div class="footer">footer</div>

Related