Search code examples
cssbackground-imageshadow

CSS - Element with 2 background images - How to drop shadow just around one of them?


I have a div element with two background images, both added using JavaScript. The first background image, at the top of the div, is set according to "data-img" attribute, while the second one is always the same.

HTML

<div class="card" data-img="https://placehold.co/130x130"></div>

JS

document.querySelectorAll(".card").forEach(card => 
card.style.background = "url(" + card.dataset.img + ") no-repeat center top 20px, url(https://placehold.co/50x50) no-repeat center bottom 20px");

Is it possible - using "filter: drop-shadow", or in another way - to drop shadow just around the first image?

document.querySelectorAll(".card").forEach(card => 
card.style.background = "url(" + card.dataset.img + ") no-repeat center top 20px, url(https://placehold.co/50x50) no-repeat center bottom 20px");
.card {
border: 1px solid black;
height: 250px;
width: 200px;
}
<div class="card" data-img="https://placehold.co/130x130"></div>


Solution

  • Use a pseudo-element an inherit the background from the main element then make the size of the second one 0 and apply filter to it.

    document.querySelectorAll(".card").forEach(card =>
      card.style.background = "url(" + card.dataset.img + ") no-repeat center top 20px, url(https://placehold.co/50x50) no-repeat center bottom 20px");
    .card {
      border: 1px solid black;
      height: 250px;
      width: 200px;
      position: relative;
    }
    .card:before {
      content:"";
      position: absolute;
      inset: 0;
      background: inherit;
      background-size: auto,0 0;
      filter: drop-shadow(0 0 5px red);
    }
    <div class="card" data-img="https://placehold.co/130x130"></div>