纯 CSS实现三角形

最近项目上做评论回复,设计师提高交互性特意设计了小三角,如下:

下面介绍一下实现效果的css方法:

1.border 通过设置上下左右border宽度来实现。

  首先查看一下全部设置的效果:

<style>
  .triangle{
    width:30px;
    height:30px;
    border-width:20px;
    border-style:solid;
    border-color:#e66161 #f3bb5b #94e24f #85bfda;
}
</style>

<body>
  <div class="triangle"></div>
</body>

然后将宽高设为0,就可以得到四个三角形,单独设置一个border即可得到三角形。

 

将其他边框都设为透明,可得到三角形

代码如下:

<style>
  .triangle{
    width:0px;
    height:0px;
    border-width:20px;
    border-style: solid;
    border-color:transparent #e66161 transparent transparent;
  }
</style>

<body>
  <div class="triangle"></div>
</body>

     要想实现项目要求的样式,需要些两个三角形重叠,然后外面的比内层的多出1px做边框,利用两个三角的背景色差实现border效果,

     

代码如下:

<style>
  .triangle{
    width:0px;
    height:0px;
    border-width:20px;
    border-style: solid;
    border-color:transparent #C9E9C0 transparent transparent;
  }
  .triangle-border{
    margin-left: 1px;
    margin-top: -40px;
    width:0px;
    border-width:20px;
    border-style: solid;
    border-color:transparent #E9FBE4 transparent transparent;
  }
</style>

<body>
  <div class="triangle"></div>
  <div class="triangle-border"></div>
</body>

 

2 特殊字符 ◆ 来实现。

   这种方法的场景是和矩形框结合,将◆的背景色设置为矩形框的颜色即可。这里就不写矩形框了。通过调整font来实现调整三角形大小。

 

代码:

<style>

  .triangle{
    overflow:hidden;
    width:26px;
    height:26px;
    font:normal 26px "宋体"; // 字符的大小和字体也有关系哦!
  }
  .tg-border {
    color:#C9E9C0;
  }
  .tg-background {
    margin-top: -25px;
    color:#E9FBE4;
  }
</style>

<body>
  <div class="triangle tg-border">◆</div>
  <div class="triangle tg-background">◆</div>
</body>

 

3,矩形旋转45度,

     缺点是不能控三角形的角度。

<style>

  .box {
    margin-top: 50px;
    position:relative;
    width:200px;
    height:50px;
    background:#E9FBE4;
    border:1px solid #C9E9C0;
    border-radius:4px;
    color:#0C7823;
  }
  .triangle{
    position:absolute;
    top:-8px;
    left:25px;
    width:13px;
    height:13px;
    background:#E9FBE4;
    border-top:1px solid #C9E9C0;
    border-left:1px solid #C9E9C0;
  }
  .transform {
    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
    transform:rotate(45deg);
  }
</style>

<body>
  <div class="box">
    <div class="triangle transform"></div>
  </div>
</body>

 

posted on 2017-06-12 14:26  jasonFED  阅读(303)  评论(0编辑  收藏  举报

导航