Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circle with transparent borders over background

How can I achieve such a thing in CSS?

Target

I've tried so many ways but the dark background is still in the way and can't be clipped so the background image under it's invisible...

.item {
  position: relative;
}
    
.item:before {
  content: '';
  size(100%);
  top: 0;
  left: 0;
  z-index: 1;
  background: rgba(0, 0, 0,0 0.1);
}
<div class="item">
   <img>
   <span class="rate">
     <span class="amount">10</span> امتیاز
   </span>
</div>  

I'm looking for a way to be able to make parts of the dark background transparent, so the image can be seen.

like image 904
Amin Avatar asked Jul 22 '20 13:07

Amin


1 Answers

This can be achieved using a radial gradient, (Example split onto separate lines to make it easier to read)

background-image: radial-gradient(
   /* Position the circle at the center, 40px from the top */
  circle at center 40px,
  /* The center of the radius should be dark */
  rgba(0,0,0,0.4) 0%,
  /* This is the inner edge of the circle, we transition from dark-transparent between pixels 30 and 31 */
  rgba(0,0,0,0.4) 30px, rgba(0,0,0,0) 31px, 
  /* This is the outer edge of the circle, we transition back from transprent-dark between pixels 34 and 35*/
  rgba(0,0,0,0) 34px, rgba(0,0,0,0.4) 35px,  
  /* Everything outside of the circle should be dark */
  rgba(0,0,0,0.4) 100%
);

Where circle at center 40px defines the position of the circle relative to the parent element (Horizontally centred, an 40px down from the top) bare in mind this is the position for the centre of the circle so you do need to account for it's radius.

And we use very small steps between the gradient to make it look like a solid line rather than a blurred gradient (I find that a 1px difference helps prevent aliasing on the line and makes everything look much smoother)

You can adjust the size of the circle or the thickness of the line by changing the 30px, 31px, 34px and 35px values in the gradient.

Working example:

.item {
  position: relative;
  width: 200px;
  height: 200px;
  background: url(https://picsum.photos/seed/picsum/200/200);
}

.item:before {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  /* This is the ring itself, you can adjust it's size using the pixel values, leaving 1px differnce usually leaves the best result for smooth edges */
  background-image: radial-gradient(circle at center 40px, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0.4) 30px, rgba(0, 0, 0, 0) 31px, rgba(0, 0, 0, 0) 34px, rgba(0, 0, 0, 0.4) 35px, rgba(0, 0, 0, 0.4) 100%);
}
<div class="item"></div>

(This method is browser compatible with pretty much every browser released since 2010)

like image 118
DBS Avatar answered Oct 15 '22 12:10

DBS