HTML / CSS如何使元素对一个元素透明但对另一个元素覆盖

时间:2018-08-16 21:54:41

标签: html css

所以,我有这个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>

我需要使绿色正方形对背景透明,但将红色正方形覆盖。而且我需要将其变量设置为变量,这样我就不能这样:.div2 {background-color: lightblue;}。可以通过吗?

2 个答案:

答案 0 :(得分:1)

对红色正方形使用渐变:

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>

更新

您可能正在寻找这样的东西:

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>

答案 1 :(得分:0)

使用background-color: inherit;覆盖。

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>