Draw triangle in corner of div

前端 未结 4 1326
夕颜
夕颜 2021-01-02 09:20

I\'d like to draw some kind of triangle in the corner of a div. Because I don\'t want to use "px" I\'d like to achieve the same result also with percentage values.

4条回答
  •  滥情空心
    2021-01-02 10:22

    You can use position: absolute on triangle element and set top and right properties to 0.

    .container {
      position: absolute;
      top: 5%;
      left: 5%;
      width: 60%;
      height: 30%;
      background: black;
      color: white;
      border-radius: 12px;
      overflow: hidden;
    }
    
    .triangle {
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 0 30px 30px 0;
      border-color: transparent #608A32 transparent transparent;
      right: 0;
      top: 0;
      position: absolute;
    }

    You can also just use pseudo-element with absolute position for triangle.

    .container {
      position: relative;
      width: 300px;
      height: 70px;
      background: black;
      border-radius: 12px;
      overflow: hidden;
    }
    
    .container:after {
      content: '';
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 0 30px 30px 0;
      border-color: transparent #608A32 transparent transparent;
      right: 0;
      top: 0;
      position: absolute;
    }

    Below is another example with triangles in all corners.

    .all_triangles_container {
      position: relative;
      width: 300px;
      height: 70px;
      background: black;
      overflow: hidden;
    }
    
    .triangle {
      width: 0;
      height: 0;
      border-style: solid;
      position: absolute;
    }
    
    .triangle_tl {
      border-width: 0 0 30px 30px;
      border-color: transparent transparent transparent green;
      left: 0;
      top: 0;
    }
    
    .triangle_tr {
      border-width: 0 30px 30px 0;
      border-color: transparent red transparent transparent;
      right: 0;
      top: 0;
    }
    
    .triangle_br {
      border-width: 30px 30px 0 0;
      border-color: transparent yellow transparent transparent;
      right: 0;
      bottom: 0;
    }
    
    .triangle_bl {
      border-width: 0 30px 30px 0px;
      border-color: transparent transparent purple transparent;
      left: 0;
      bottom: 0;
    }

提交回复
热议问题