skip to Main Content

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>

2

Answers


  1. You could use a pseudo-element. Sadly, the support for url(data-img, url) is non-existant, but you can set a CSS variable on your element that points to your URL, and add that as the content for your pseudo-element. Then it’s merely to add a box-shadow to your pseudo-element.

    Bonus: no javascript required.

    .card {
      position: relative;
      border: 1px solid black;
      height: 250px;
      width: 200px;
      background: url(https://placehold.co/50x50) no-repeat center bottom 20px;
    }
    
    .card::before {
      content: url(data-img, url); /* Proposed for future CSS, but doesn't work */
      content: var(--background);
      position: absolute;
      z-index: -1;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      box-shadow: 2px 2px 8px 0px #333;
    }
    <div class="card" style="--background: url(https://placehold.co/130x130)"></div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search