如何在CSS中实现角度边界

时间:2018-10-31 20:38:31

标签: css

enter image description here

我想为div制作四个角度边框,如图所示。我看到有人使用<fieldset>隐藏边框的一部分,但这不是我想要的。有没有简单的方法可以做到这一点?

3 个答案:

答案 0 :(得分:1)

CSS Border Image与仅包含拐角内容的源图像一起使用。这样可以避免不必要的html元素或伪元素。此示例使用内联到CSS中的SVG作为源图像。

.angled-borders {
  border: 10px solid;
  border-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 11 11' width='11' height='11'><g fill='%23489fe2'><rect width='1' height='5'/><rect y='6' width='1' height='5'/><rect x='10' y='6' width='1' height='5'/><rect x='10' width='1' height='5'/><rect width='5' height='1'/><rect y='10' width='5' height='1'/><rect x='6' y='10' width='5' height='1'/><rect x='6' width='5' height='1'/></g></svg>") 5;
}
div {
  display: inline-block;
  padding: 1rem;
}
<div class="angled-borders">content</div>

编辑:转义数据URI中的哈希。谢谢,@ AuxTaco。

答案 1 :(得分:0)

如果不需要背景是透明的,就是这种情况。

div{
  width: 100px;
  height: 50px;
  border: 2px solid blue;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  font-size: 30px;
  box-sizing: border-box;
}

div span{
  position: relative;
  z-index: 2;
}


div::before,
div::after{
  content: "";
  position: absolute;
  z-index: 1;
  background: #fff;
}

div::before{
  width: calc(100% + 4px);
  height: calc(100% - 20px);
  left: -2px;
}

div::after{
  width: calc(100% - 20px);
  height: calc(100% + 4px);
  left: 50%;
  transform: translateX(-50%);
}
<div>
  <span>
    1
  </span>
</div>

答案 2 :(得分:0)

如果背景是纯色(表示您不关心透视元素),则可以轻松地做到这一点。

基本上,我们只是将伪元素放置在边框的顶部,其颜色与背景颜色相同,因此边框看起来是隐藏的。

div.outer {
  width: 200px;
  height: 200px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.2);
  /* keep absolute position childern in place */
  position:relative;
  
  /*full border*/
  border: 5px solid blue;

  /*background so we can see what happens*/
  background-color:#eee;
  }
 
 div.inner {
  line-height: 160px;
  padding: 20px;
  text-align: center;
  position: relative;
  z-index:10;
 }
 
 
 div.outer:before, div.outer:after {
  content:"";
  position: absolute;
 
  /*hide stuff*/
  background-color: #eee;
 }
 
 div.outer:before {
  top:-5px; /*width of border subtracted from top*/
  left:5%; /*push in 5% from the sides */
  bottom:-5px;
  right: 5%;
 }
  div.outer:after {
  top:5%; /*push in 5% from the sides */
  left:-5px; /*width of border subtracted from top*/
  bottom:5%;
  right: -5px;
 }
 
  
<div class="outer">
<!-- sadly we need two divs to move the content forward -->
  <div class="inner">
  Content
  </div>
</div>