loumadev
loumadev

Reputation: 369

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?

Upvotes: 0

Views: 151

Answers (2)

Temani Afif
Temani Afif

Reputation: 273010

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>

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

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>

Upvotes: 0

Related Questions