用css样式画三角形(提示框三角形)

转载自https://blog.csdn.net/hope_It/article/details/70217954

  • 经常用于提示框,下拉菜单等(csdn也很多用到,最后一图)
  • 三角形画法

  • html结构 
    <div class="triangle"> 
    </div>
  • 三角形画法 
    • 用border画出,当width、height均为100px时
  •     .triangle {
            width: 100px;
            height: 100px;
            border-left: 10px solid #7d7b7b;
            border-top: 10px solid #5851c3;
            border-right: 10px solid #21a4d6;
            border-bottom: 10px solid #4ed621;
            box-sizing: border-box;
        }
  •  
  • –>结果:border 
    改变{width:0; height:0}–>这里写图片描述

    –>再去掉border-top—>这里写图片描述

    –>可以看见上面的一半已经没有了

    –>设置左右两边border-color:transparent; –> 这里写图片描述 
    –>就得到了想要的三角形了,这是向上的,想要哪边就画哪边的border,并且让它相邻两边的border-color:transparent

    –>代码

        .triangle {
            width: 0;
            height: 0;
            border-left: 10px solid transparent;
            /*border-top: 10px solid #5851c3;*/
            border-right: 10px solid transparent;
            border-bottom: 10px solid #4ed621;
            box-sizing: border-box;
        }
  •  
  • 画提示框三角形(有边缘的)

    如图:边缘三角形

  • 原理:先画一个三角形,再画白色三角形的,调整几像素位置,覆盖掉一边
  • –> 这里写图片描述

  • 代码
  •  .triangle {
            position: relative;
            width: 100px;
            height: 50px;
            border: 2px solid #4ed621;
            border-radius: 5px;
        }
    
        .triangle:before {
            position: absolute;
            content: "";
            top: -10px;
            left: 25px;
            border-left: 10px solid transparent;
            border-right: 10px solid transparent;
            border-bottom: 10px solid #4ed621;
        }
        /* 白色覆盖*/
        .triangle:after {
            position: absolute;
            content: "";
            /*减少两像素*/
            top: -8px;
            left: 25px;
            border-left: 10px solid transparent;
            border-right: 10px solid transparent;
            border-bottom: 10px solid #fff;
        }
          <div class="triangle"></div>
  •  
  • 结果: 
    –> hh–>h

  • 至此,三角形画完,只用到了css2的属性,兼容性一览无余
  • 推荐一款优秀的在线画图工具,很不错(不是广告啊!)

猜你喜欢

转载自blog.csdn.net/see__you__again/article/details/82108920