Search code examples
htmlcssbordercss-gradientscss-mask

Adding an outer gradient border or overlay shape to a circular image using CSS


I'm attempting to add an outer gradient border of three solid colors (Fig B) to an image (Fig A) using CSS, but am not having much luck with the methods I've tried thus far. The images will have border-radius: 50% to make them circular and the outer border needs to scale with the image. I'd like to be able to quickly apply this to any image using only a CSS class.

I've tried SVG masks, border-images, and regular overlays but none seem to accomplish the task at hand. This pen is the closest I've gotten, however I need whitespace between the image and border.

.img-circle{
  border-radius: 50%;
} 
.border {
  margin: 25px 0;
  /*padding: 1em;*/
  border: 12px solid transparent;
  background-size: 100% 100%, 60% 60%, 40% 40%, 25% 50%;
  background-repeat: no-repeat;
  background-image: linear-gradient(white, white),
    linear-gradient(30deg, teal 36%, teal 30%),
    linear-gradient(120deg, gold 36%, gold 30%),
    linear-gradient(210deg, blue 36%, blue 30%);
  background-position: center center, left top, right top, left bottom, right bottom;
  background-origin: content-box, border-box, border-box, border-box;
  background-clip: content-box, border-box, border-box, border-box;
}
<img src="https://placeimg.com/280/280/any" class="border img-circle">

Any thoughts on how I should approach this?

Example of what I'd like


Solution

  • I would do it like below. Two radial-gradient for the circles, a conic-gradient for the remaining coloration and a mask to create the gap:

    .img-circle{
      border-radius: 50%;
    } 
    .border {
      padding: 2em;
      background:
       radial-gradient(farthest-side,teal 98%,#0000) 33%  97%/1em 1em,
       radial-gradient(farthest-side,gold 98%,#0000) 100% 50%/1em 1em,
       conic-gradient(from -160deg, teal 120deg, blue 0 210deg,gold 0 250deg,#0000 0);
      background-repeat:no-repeat;
      -webkit-mask:
        radial-gradient(farthest-side, 
         #000  calc(99%  - 2em),
         #0000 calc(100% - 2em) calc(99% - 1em), 
         #000  calc(100% - 1em))
    }
    
    body {
      background:#ccc;
    }
    <img src="https://placeimg.com/280/280/any" class="border img-circle">