Search code examples
javascripthtmlcssmix-blend-mode

Change background and font color of fixed positioned div based on background


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="background1">Div1</div>
    <div class="background2">Div2</div>
    <div class="background3">Div3</div>
    <div class="background4">Div4</div>
    <div class="fixed-background">This should change color based on background</div>

</body>
</html>




div {
    height: 100vh;
}

.background1 {
    background: gray;
}

.background2 {
    background: black;
}

.background3 {
    background: blue;
}

.background4 {
    background: tomato;
}

.fixed-background {
    position: fixed;
    top: 10px;
    left: 10px;
    width: 100px;
    height: 100px;
    mix-blend-mode: difference;
}

Hello everybody, I try to change the background and color of the div with class fixed-background based on the background of the other div. I came across the mix-blend-mode CSS property, but it seems not to work.

I´m by far no CSS Expert, can anyone help me to get this working? I would not be unhappy if I get it working with a JS function.


Solution

  • I've been playing around with mix-blend-mode and maybe I've got what you need. Check it, please. An important thing is you have to check compatibility with browsers.

    https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode

    body {
      margin-bottom: 50vh;
    }
    
    .background1,
    .background2,
    .background3,
    .background4 {
      height: 50vh;
    }
    
    .background1 {
      background: gray;
    }
    
    .background2 {
      background: black;
    }
    
    .background3 {
      background: blue;
    }
    
    .background4 {
      background: tomato;
    }
    
    .fixed {
      position: fixed;
      top: 10px;
      right: 10px;
      width: 100px;
      height: 100px;
      mix-blend-mode: screen;
    }
    
    .fixed-text {
      background: green;
      color: maroon;
      mix-blend-mode: difference;
      z-index: 3;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }
    <div class="background1">Div1</div>
    <div class="background2">Div2</div>
    <div class="background3">Div3</div>
    <div class="background4">Div4</div>
    <div class="fixed">
      <div class="fixed-text">
        This should change color based on background
      </div>
    </div>