Search code examples
htmlcssimagebox-shadow

Box-shadow on image using HTML vs CSS


The only working solution I've come across to put an image in a div, give it a border radius and drop a box-shadow over it is to put the URL to the image in the CSS like so:

.score-image {
  border-radius: 5% 10% 15% 20%;
  box-shadow: inset 0 0 55px rgba(0, 0, 0, 1.0);
  width: 400px;
  height: 400px;
}

#score-image-1 {
  background: blue url('https://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded') no-repeat center;
  background-size: cover;
}
<div class="score-image" id="score-image-1">
</div>

However I feel like these images are content, and in the interests of seperating content from presentation I'd like to put an image in a div in the HTML and drop the shadow over it with the CSS without using absolute positioning like is found in other solutions. Is this possible? It seems like the image always appears over the inset box-shadow, even when I create extreme Z-indexes to push the shadow out or bring the image back.

I've tried a number of different things but this is how I'd like to see it work:

	.score-image {
		border-radius: 5% 10% 15% 20%;
		box-shadow: inset 0 0 55px rgba(0, 0, 0, 1.0);
	}
 <div class="scores">
      <div class="score-image" id="score-image-1">      
        <img src="https://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded" alt="Image">    
      </div>
    </div>

Any ideas on how to achieve this in a reasonable way, or is this a case where I just need to get over it and do it in the CSS?


Solution

  • Unfortunately the box-shadow is part of the parent element so you have to use either a shadow element or a psuedo element.

    HTML

    <div class="img">
      <img src="https://avatars2.githubusercontent.com/u/1918732?s=460&v=4">
    </div>
    

    CSS

    img {
      display: block;
    }
    
    .img {
      border-radius: 20px;
      display: inline-block;
      overflow: hidden;
      position: relative;
    }
    
    .img:before {
      border-radius: 20px;
      bottom: 0;
      box-shadow: inset 0 0 10px 10px #000;
      content: " ";
      left: 0;
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1;
    }
    

    Demo