Thanks for taking the time to read my post. So I've started freelancing recently (CSS and HTML) and I've found my first difficulty.

First example image

Look at the green bar (Its a fixed div), its green for testing porpuses, but client wants it to be transparent when on top of this orange background...

second example image

...But switch to another color when on top of this white background (So the letters can be seen)

Is this possible to do with CSS? If so, how do I do it? Thanks again!

2 Answers

2
Seph Reed On

Pure css does not currently have any amount of responsiveness to what is and is not onscreen. So, the short lame answer is "not with just css."

That being said, it's very easy to do this with js.

The event you'll be looking for is scroll event.

From there you can add/remove a class for styling.

Something like this:

// wait for document.addEventListener("DOMContentLoaded");

const myHeader = document.getElementById("MyHeader");
window.addEventListener("scroll", () => {
  const scrollPos = window.scrollY;
  if (scrollPos ... add your logic here) {
    myHeader.classList.add("scrollIsThing");  // this is the css class you'll target
  } else {
    myHeader.classList.remove("scrollIsThing");
  }
});

Sorry there's no good css way to do this.

0
Piotr Wicijowski On

It is "kind of" possible to do this just with css if you can accept some html markup duplication. You can split the fixed header into two layers, one for white text, one for background, and using z-index you can sandwich the content between these two header layers (in case of a colorful content), in which case only the white text would be visible, and position the white content below the header background. A sample of such behavior is shown below:

.header {
  height: 50px;
  background: transparent;
  position: fixed;
  top: 0;
  width: 100%;
  color: white;
  font-family: sans;
  text-align: center;
  line-height: 50px;
  z-index: 3;
}

.header.header-background {
  background: teal;
  z-index: 1;
}

.body1 {
  height: 120vh;
  background: orange;
  z-index: 2;
  position: relative;
}

.body2 {
  height: 120vh;
  background: #eee;
  
}

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  
}
<div class="header">
  White text
</div>
<div class="body1"></div>
<div class="header header-background">

</div>
<div class="body2"></div>