前端基础CSS——CSS实现带尖角的有背景颜色的正方形

前端开发过程中,下面这样的图标经常会遇到,当然,最简单的方法是找UI切个背景图,但是,代码的世界也不能完全靠图,那么,用css又该如何实现呢,研究了网上的大多数方法,核心就是:定位+拼图

1,先画个长方形,设置相对定位,很简单,不多说

.triangle{
    width:74px;
    height:20px;
    border: 1px rgba(38,110,237,0.44) solid;
    background-color:rgba(38,110,237,0.1);
    position:relative;
    border-radius: 2px;
}

2,需要画一个三角形拼在左边,变成下面这个样子

.triangle:before{
    width:0px;
    height:0px;
    border:transparent solid;
    position:absolute;
    right:100%;
    content:"";
    border-width:10px;
    border-right-color: rgba(38,110,237,0.44); //边框颜色和长方形背景颜色保持一致
    top:-1px;
}


是不是有点突兀,怪怪的,不急,来点补救,

3,再画一个白色三角形,让第二步的三角形看起来只有一个边边【如果背景颜色没有透明度,这步可省略,直接下一步】

.triangle:after{
    width: 0px;
    height: 0px;
    border: transparent solid;
    position: absolute;
    right: 71px;
    content: "";
    border-width: 9px;
    border-right-color: #fff;
    top: 0px;
}

然后,就变成了这样  

4,再画一个和长方形一样的三角形补上就ok啦      tip:这是定位在长方形里的一个小元素

.blank1{
    width:0px;
    height:0px;
    border:transparent solid;
    position:absolute;
    border-width:8px;
    border-right-color: rgba(38,110,237,0.1);
    top:1px;
    right: 72px;
    z-index: 2;
}

然后就成了这个样子,作为一个严谨的开发,怎么能有瑕疵呢,决定再补一下

5,再画一个小小的线条把中间的空隙补充完整

.line1{
    width: 1px;
    height: 19px;
    position: absolute;
    right: 71px;
    top: -1px;
    background-color: rgba(38, 110, 237, 0.1);
    border-top: 1px solid rgba(38, 110, 237, 0.44);
    border-bottom: 1px solid rgba(38, 110, 237, 0.44);
    z-index: 10;
}

ok,完工,还算完美

最后再附上完整的代码

<div class="triangle"><i class="blank1"></i><i class="line1"></i></div>
.triangle{
    width:74px;
    height:20px;
    border: 1px rgba(38,110,237,0.44) solid;
    background-color:rgba(38,110,237,0.1);
    position:relative;
    border-radius: 2px;
}
.triangle:before{
    width:0px;
    height:0px;
    border:transparent solid;
    position:absolute;
    right:100%;
    content:"";
    border-width:10px;
    border-right-color: rgba(38,110,237,0.44); //边框颜色和长方形背景颜色保持一致
    top:-1px;
}

.triangle:after{
    width: 0px;
    height: 0px;
    border: transparent solid;
    position: absolute;
    right: 71px;
    content: "";
    border-width: 9px;
    border-right-color: #fff;
    top: 0px;
}
.blank1{
    width:0px;
    height:0px;
    border:transparent solid;
    position:absolute;
    border-width:8px;
    border-right-color: rgba(38,110,237,0.1);
    top:1px;
    right: 72px;
    z-index: 2;
}
.line1{
    width: 1px;
    height: 19px;
    position: absolute;
    right: 71px;
    top: -1px;
    background-color: rgba(38, 110, 237, 0.1);
    border-top: 1px solid rgba(38, 110, 237, 0.44);
    border-bottom: 1px solid rgba(38, 110, 237, 0.44);
    z-index: 10;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章