lucky1928
lucky1928

Reputation: 8841

css - clip image and add border to fit in div

I wish to clip a 80px circle from image src to add a red border (circle) around the clipped portion then fit to a div box.

Below is a example but the red border not work. I would like the clipped portion to fit to the div only but now the div size is the original image size.

.my-clip {
  position: absolute;
  clip-path: circle(80px at 50% 25%);
  border:1px solid red;//wish to get a circle border around the clipped portion
  background-color: #bdbdbd;
  box-sizing: border-box;
}

.square {
     position: relative;
     width: 300px;     
     height: 300px;
     overflow: hidden;
     border: 1px solid red;
  }
<div class="square">
<img class="my-clip"  src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/300px-Tux.svg.png" alt="alternatetext">
</div>

Update: I try to use calc function to change the position but looks like the math is not correct!

.my-clip {
  position: absolute;
  --x: 150px;
  --y: 100px;
  left: calc(80px + 5px - var(--x));
  top: calc(80px + 5px - var(--y));
  clip-path: circle(80px at var(--x) var(--y));
  background-color: #bdbdbd;
}

.square {
     position: relative;
     width: 170px;     
     height: 170px;
     overflow: hidden;
     border: 5px solid lightgray;
     border-radius:50%;
  }
<div class="square">
<img class="my-clip"  src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/300px-Tux.svg.png" alt="alternatetext">
</div>

Upvotes: 1

Views: 1792

Answers (1)

Temani Afif
Temani Afif

Reputation: 272901

Adjust the different values and you can do it with border-radius:

.my-clip {
  position: absolute;
  left: 50%;
  top: -6%;
  transform: translate(-50%);
  /*clip-path: circle(80px at 50% 25%); no more needed*/
  background-color: #bdbdbd;
}

.square {
  position: relative;
  width: 160px;
  height: 160px;
  overflow: hidden;
  border: 1px solid red;
  border-radius: 50%;
}
<div class="square">
  <img class="my-clip" src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/300px-Tux.svg.png" alt="alternatetext">
</div>

Upvotes: 1

Related Questions