Div 边框内有透明间隙

Div with transparent gap inside border

我有一个大小不一的 div,需要有一个透明区域后跟一个白色边框,如以下屏幕截图所示:

我很容易获得正确的红色透明度和形状,但我不知道如何获得透明区域后跟白色边框。我该怎么做?

Link 到 Fiddle

div{
    background: #f00;
    height: 100px;
    width: 100px;
    border-radius: 100px;
    position: relative;
}
div:before{
    content: '';
    top: -5px;
    bottom: -5px;
    left: -5px;
    right: -5px;
    border: 3px solid #000;
    border-radius: 100px;
    position: absolute;
}

您在背景颜色和边框之间创建了一个间隙,方法是:

  • 一个元素。
  • 透明边框,使框阴影和背景之间形成透明间隙。
  • background-clip:padding-box;将背景裁剪在透明边框内(否则背景颜色会溢出并透过透明边框出现,more info here)。
  • a box-shadow 外线的扩展半径。

div {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: rgba(255, 0, 0, .7);
  border: 10px solid transparent;
  background-clip: padding-box;
  box-shadow: 0 0 0 4px #fff;  
}

/** FOR THE DEMO **/
body {background: url('https://farm9.staticflickr.com/8760/17195790401_ceeeafcddb_o.jpg');background-size: cover;}
<div></div>

我也试过:http://jsfiddle.net/6o26j9e9/ 文本居中 :D

body {
    background-color: #333;
    background: url('http://www.awesomeimages.net/wp-content/uploads/2011/09/4011001045_50701c52ff_b1.jpg');
    background-size: cover;
}

.border {
    width: 500px;
    height: 500px;
    border-radius: 1000px;
    border-radius: 50%;
    border: 2px solid #FFF;
    padding: 15px;
    display: table;
}

.circle {
    width: 100%; height: 100%;
    border-radius: 1000px;
    border-radius: 50%;
    background: rgba(255,0,0,0.6);
    text-align: center;
    color: #FFF;
    display: table-cell;
    vertical-align: middle;
    font-size: 70px;

}

更新:http://jsfiddle.net/6o26j9e9/1/

也可以使用径向渐变:

#test {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 120px center, 
      rgba(255, 0, 0, .5) 100px,
      rgba(255, 0, 0, 0) 100px,
      rgba(255, 255, 255, 0) 105px,
      rgba(255, 255, 255, .5) 105px,
      rgba(255, 255, 255, .5) 110px,
      rgba(255, 255, 255, 0) 110px
    ),
    url(http://lorempixel.com/output/nature-q-c-1280-960-5.jpg) center/cover;
}
<div id="test"></div>

径向渐变增加了优势。例如,您可以绘制椭圆而不是圆,添加更多边框并创建更复杂的图案。