首页 > 解决方案 > 如何添加透明边框?

问题描述

我有一个简单的用户个人资料图像和一个绿色状态指示器。

我想为指示器添加一个透明边框,它超过了背景中的图像,如下图所示。

期待结果

当背景是单色时很容易,我只需要添加一个相同颜色的边框,但是当背景是渐变或图像时怎么办?如果我添加一个白色边框,它看起来像中间的图像,我想要一个像右图一样的渲染。

如何做到这一点?

.user {
  display: inline-block;
  position: relative;
}
img {
  width: 75px;
  height: 75px;
  border-radius: 75px;
}
.user-state {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 15px;
  height: 15px;
  border-radius: 10px;
  background: #57d642;
}
<body>
  <div class="user">
    <img src="http://lorempicsum.com/up/255/200/5" alt="">
    <div class="user-state"></div>
  </div>
</body>

标签: htmlcssborder

解决方案


我会考虑 SVG 和掩码,如下所示:

.user {
  display: inline-block;
  position: relative;
}

svg {
  width: 200px;
  height: 200px;
}

.user:after {
  content: "";
  position: absolute;
  top: 18px;
  right: 18px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #57d642;
}

body {
  background: linear-gradient(to right, pink, purple);
}
<div class="user">
  <svg viewbox="0 0 200 200">
  <defs>
    <mask id="hole">
      <rect width="100%" height="100%" fill="white"/>
      <!-- This circle is your hole on the top -->
      <circle r="28" cx="162" cy="38" fill="black"/>
    </mask>
    <!-- the clipath will replace border-radius -->
    <clipPath id="circle">
       <circle cx="100" cy="100" r="100" fill="white" />            
    </clipPath>
  </defs>
<image width="200" height="200" xlink:href="https://picsum.photos/id/1003/200/200" mask="url(#hole)" clip-path="url(#circle)"/>
</svg>
</div>


推荐阅读