7

I was wondering if a solution exists in pure CSS to color the intersection between two divs.

For exemple, if I have two divs, with the same class like this:

<div class="orange_square"></div>
<div class="blue_square"></div>

They are placed on the page so they so they overlap, like this:

enter image description here

I want the intersection of these two divs to be colored in red, and this in CSS only. I was wondering if something like this existed:

.orange_square {
   background-color:orange;
}
.blue_square {
   background-color:blue;
}
.orange_square [overlap_operator?] .blue_square {
   background-color:red;
}

Is that possible?

Lord Grosse Jeanine
  • 1,111
  • 10
  • 29

2 Answers2

5

Unfortunately, not in 'Pure CSS'

(sorry)

However...

Although there isn't a way to automatically calculate & define define such a area purely in CSS, if you know the dimensions of the two 'parent' divs, you can hard code it without adding additional DOM clutter, which is going to be as close as you can get just using CSS and div elements:

Demo Fiddle

HTML

<div></div>
<div></div>

CSS

div {
    position:absolute;
    height:100px;
    width:100px;
}
div:first-of-type {
    background:orange;
}
div:last-of-type:before {
    content:'';
    height:33px;
    width:33px;
    display:block;
    position:absolute;
    background:red;
}
div:last-of-type {
    background:lightblue;
    top:75px;
    left:75px;
}
SW4
  • 69,876
  • 20
  • 132
  • 137
  • I think the OP wants something like *color combination* which is very dynamic, such as if changing the orange to blue, the intersected region should have another color than the fixed `red`. – King King May 19 '14 at 14:51
  • @KingKing - absolutely, as noted in the answer - although they as requested 'in pure CSS' there isnt a way as far as I'm aware – SW4 May 19 '14 at 14:52
  • In fact, I just want a way to detect when two divs overlap. Then, I would be able to color it as I want. I'm making a timeline with events (colored divs) and I want to color in red when tow events overlap in my timeline. But it seems like it's not possible in pure CSS. I'm pretty sure that I will achieve this in JS but a pure CSS solution would have been wonderful ^^ Thanks for your help anyway. – Lord Grosse Jeanine May 19 '14 at 14:56
  • @PiTiNiNjA - sadly, this isnt possible without resorting to JS – SW4 May 19 '14 at 14:57
4

You can try the mix-blend-mode property.

.orange_square,
.blue_square {
    position:absolute;
    height:100px;
    width:100px;
}

.orange_square {
    background: orange;
}

.blue_square {
    background: blue;
    top:75px;
    left:55px;
    
    /* the trick */
    mix-blend-mode: color-burn;
}
<div class="orange_square"></div>
<div class="blue_square"></div>

Tip: always check the compatibility table https://caniuse.com/#feat=css-mixblendmode

leonardomerlin
  • 120
  • 1
  • 7