To achieve multiple background colors in CSS, a common proposal is
But there is an alternative:
- Solid Color
background-images
via SVG Data URIs
The working example below contains the following areas with the following background colors:
<main>
- dark-gray
<section>
- light-gray
<div class="circle">
- translucent red
In this set-up, we want to use the same theme-color for all the circles, rgba(255, 0, 0, 0.5)
but we also want the circles inside the <section>
to appear to have the same background-color
as the circle outside <section>
.
We can observe that, due to the application of the technique below to div.circle.does-not-blend
- the rightmost of the two circles inside <section>
- that circle ends up with the same apparent background-color
as div.circle
outside <section>
.
The Approach
The approach is to give div.circle.does-not-blend
:
- the same initial
background-color
as <main>
- an SVG Data URI
background-image
with the same translucent red background-color
as the other .circle
elements
The SVG background-image
The SVG Data URI background-image
looks like this:
data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" style="background-color:rgba(255, 0, 0, 0.5);"%2F%3E
The Result
In the final result we see that the light-gray background-color
of <section>
does not bleed through and influence the final background-color
of div.circle.does-not-blend
Working Example
main {
display: flex;
justify-content: space-around;
align-items: center;
height: 180px;
padding: 0 9px;
background-color: rgb(127, 127, 127);
border: 1px solid rgb(0, 0, 0);
}
section {
display: flex;
justify-content: space-around;
align-items: center;
flex: 0 0 66%;
background-color: rgb(191, 191, 191);
height: 162px;
}
.circle {
display: inline-block;
width: 120px;
height: 120px;
color: rgb(255, 255, 255);
text-align: center;
line-height: 120px;
background-color: rgb(255, 0, 0, 0.5);
border-radius: 50%;
}
.circle.does-not-blend {
background-color: rgb(127, 127, 127);
background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" style="background-color:rgba(255, 0, 0, 0.5);"%2F%3E');
}
<main>
<div class="circle"></div>
<section>
<div class="circle">Incorrect</div>
<div class="circle does-not-blend">Correct</div>
</section>
</main>