JORDAN GAUTHIER
JORDAN GAUTHIER

Reputation: 11

Creating a z-index like effect

I'm not a front end developer so sorry if my question look easy. I search the whole day figuring out how to create a z-index like effect but with a special condition. (Z-index don't work for what I want to accomplish and it's normal).

I would like to find a way to make the text disappear and appear when it cross a div. But the problem that I have with z-index is the following : the text of the first div do not disapear when it cross the red div.

https://jsfiddle.net/2bry9nuj/20/

<div id="firstDiv">
    <h1 style="">text first div</h1>
</div>
<div id="secondDiv">
   <h1>text second div</h1>>
</div>
#firstDiv
{
 position: relative;
 width: 100%;
 height: 500px;
 background-color:green;
 z-index: 1;
}

#secondDiv
{
  position: relative;
  width: 100%;
  height: 500px;
  background-color: red;
}

h1
{
  position:fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
}

If you don't understand the problem properly you can see a demo on the homepage of this website just scroll down and you will see. https://www.lucidmotors.com/

Upvotes: 1

Views: 83

Answers (2)

Temani Afif
Temani Afif

Reputation: 273481

You are almost good, you simply need to clip the text to its section. You can use clip-path for this

#firstDiv {
  position: relative;
  width: 100%;
  height: 500px;
  background-color: green;
}

#secondDiv {
  position: relative;
  width: 100%;
  height: 500px;
  background-color: red;
}

h1 {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
}

#firstDiv,
#secondDiv {
  clip-path:inset(0);
}
<div id="firstDiv">
  <h1 style="">text first div</h1>
</div>
<div id="secondDiv">
  <h1>text second div</h1>
</div>

Upvotes: 2

lolc
lolc

Reputation: 153

position:fixed doesnt respect z-index cause of the CSS spec or whatever, so you need javascript for this. Please take a look at the following code

text = document.getElementsByTagName("h1");

window.addEventListener("scroll",scroll);

bounds = [];
for(i=0; i<text.length; i++){
    bounds.push(text[i].getBoundingClientRect());
}
scroll();

function scroll(){
  for(i=0; i<text.length; i++){
    text[i].style.top = this.scrollY - bounds[i].top + "px";
  }
}
body{
  margin:0;
}

#firstDiv, #secondDiv{
  height:100vh;
  background:grey;
  overflow:hidden;
  position:relative;
}

#secondDiv{
  background:tomato;
}

h1{
  position:absolute;
  text-align:center;
  line-height:100vh;
  width:100%;
}
<div id="firstDiv">
   <h1>
      test1
   </h1>
</div>
<div id="secondDiv">
   <h1>
      test2
   </h1>
</div>

cheers

Upvotes: 1

Related Questions