CSS - Color divs intersection

杀马特。学长 韩版系。学妹 提交于 2020-12-29 12:12:29

问题


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?


回答1:


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;
}



回答2:


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



来源:https://stackoverflow.com/questions/23740740/css-color-divs-intersection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!