How to invert stroke text color depending on backg

2020-04-16 18:22发布

问题:

I have 2 divs 50% width each. There is a huge header h1 which should have the color of these two divs. I have tried mix-blend-mode but it gives me some random colors when set to difference. My goal is to invert the colors but to keep the colors of the divs. This is a codepen file, I have tried to keep it as simple as possible: https://codepen.io/lukagurovic/pen/MLoZmj The final effect is supposed to look like on in this example:

https://jsfiddle.net/1uubdtz6/

but I am not sure why doesn't it work with these colors. Also, these divs are interactive so the color has to change dynamicly as divs are increasing in width when hovered, and there should be only stroke of text without any fill

body {
  height: 100vh;
  width: 100%;
  position: relative;
  background-color: #510035;
  margin: 0 auto;
}   

h1 {
  font-size: 4.7em;
  text-transform: uppercase;
}

.half-pager {
  width: 50%;
  height: 100%;
  position: absolute;
  display: inline-block;
  overflow: hidden;
  text-align: center;
}

.half-pager-dark {
  background-color: #510035;
}
.half-pager-light {
  right: 0;
  background-color: #E8E8E8;
  float: right;
}

.lp-header {
  position: absolute;
}
.lp-header {
  color:transparent;
  mix-blend-mode: difference;
  -webkit-text-stroke: 3px rgb(126, 124, 133); 
  z-index: 1;
}

.lp-header {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div id="box" class="half-pager half-pager-dark"></div>
<div id="box1" class="half-pager half-pager-light"></div>
<h1 class="lp-header">left or right</h1>

回答1:

One idea is to duplicate the text and use CSS variable to define the color so you can easily change them in one place. I used clip-path to hide half of one text and show the other half:

body {
  margin: 0;
  --c1:#510035;
  --c2:#E8E8E8;
}
body:hover {
  --c1:red;
  --c2:blue;
}

h1 {
  font-size: 4.7em;
  text-transform: uppercase;
  margin: 0;
}
.first {
  background:var(--c1);
  -webkit-text-stroke: 3px var(--c2);
}

.second {
  background:var(--c2);
  -webkit-text-stroke: 3px var(--c1);
  clip-path:polygon(0% 0%, 50% 0%, 50% 100%,0% 100%);
}

.lp-header {
  position:absolute;
  top:0;
  left:0;
  right:0;
  min-height:100vh;
  box-sizing:border-box;
  color: transparent;
  z-index: 1;
  padding: 50px;
  text-align: center;
  transition:0.5s;
}
<h1 class="lp-header first">left or right</h1>
<h1 class="lp-header second">left or right</h1>