简体   繁体   中英

HTML/CSS How to make element transparent for one element but overlay another

So, I have this HTML+CSS:

 body { background-color: lightblue; } .div1 { position: absolute; width: 100px; height: 100px; background-color: red; } .div2 { position: absolute; width: 80px; height: 80px; background-color: green; } 
 <!DOCTYPE html> <html> <head> </head> <body> <div class="div1"></div> <div class="div2"></div> </body> </html> 

And I need to make green square transparent for background but overlay red square. And I need to have it variable so I cannot do it like this: .div2 {background-color: lightblue;} . Is it passible?

Use gradient for the red square:

 body { background-color: lightblue; } .div1 { position: absolute; width: 100px; height: 100px; background: linear-gradient(red,red) right /20px 100%, linear-gradient(red,red) bottom /100% 20px; background-repeat:no-repeat; } .div2 { position: absolute; width: 80px; height: 80px; } 
 <div class="div1"></div> <div class="div2">div2</div> 

Update

You are probably looking for something like this:

 body { background: url(https://picsum.photos/1000/600?image=1069) fixed; } .div1 { position: absolute; width: 200px; height: 200px; background:red; } .div2 { position: absolute; width: 80px; height: 80px; top:0; left:0; background: url(https://picsum.photos/1000/600?image=1069) fixed; animation:change 2s linear infinite alternate; } @keyframes change { to{top:100px;left:100px;} } 
 <div class="div1"></div> <div class="div2">div2</div> 

Use background-color: inherit; for the overlay.

 body { background-color: lightblue; } .div1 { position: absolute; width: 100px; height: 100px; background-color: red; } .div2 { position: absolute; width: 80px; height: 80px; background-color: inherit; } 
 <!DOCTYPE html> <html> <head> </head> <body> <div class="div1"></div> <div class="div2"></div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM