Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

html - How to add a background image on top of a previous background image?

I have a css page that I am writing and I need to apply a background image in one class and then use a different class to put a partially transparent background image on top of the one that is already there. That is a bit of a word salad so let me give a bit of a demonstration.

html{
    <div class="background1">...</div>
    <div class="background1 backgroundFilter">...</div>
    <div class="background2">...</div>
    <div class="background2 backgroundFilter">...</div>
}
css {
    .background1 {
        background-image:url(...);
    }
    .background2 {
        background-image:url(...);
    }
    .backgroundFilter {
        background-image:url(...);
    }
}

In this example the first div should have background image 1, the second should have background image 1 but with the filter image placed on top of it, then the third should be image 2 and the fourth should be image 2 with the same filter on it.

In this example however .backgroundFilter would be overwriting the previous image instead of overlaying it.

Is this possible or do I need to make a different class for each version of the background image?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can consider CSS variables. Specify 2 background layer that you can change later. You can easily scale to any number of background:

.container > div {
  background:
    /*we make the default value a transparent image*/
    var(--im1,linear-gradient(transparent,transparent)),
    var(--im2,linear-gradient(transparent,transparent)); 
    
  height:200px;
  width:200px;
  display:inline-block;
}

.background1 {
  --im2: url(https://picsum.photos/200/300?image=0);
}

.background2 {
  --im2: url(https://picsum.photos/200/300?image=1069);
}

.backgroundFilter {
  --im1: linear-gradient(to right,transparent,green);;
}
<div class="container">
<div class="background1">...</div>
<div class="background1 backgroundFilter">...</div>
<div class="background2">...</div>
<div class="background2 backgroundFilter">...</div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...