Creating responsive triangles with CSS

前端 未结 3 583
一个人的身影
一个人的身影 2020-12-15 00:12

I was trying to create triangles in CSS for a responsive site today and couldn\'t find a good example on stackoverflow, so here\'s how I did it.

3条回答
  •  天命终不由人
    2020-12-15 00:22

    Reponsive triangles can be achieved with just CSS by taking advantage of padding being calculated against parent’s width to cover a big fixed-width triangle. To create an up-pointing triangle with 100% width:

    .triangle-up {
        width: 50%;
        height: 0;
        padding-left:50%;
        padding-bottom: 50%;
        overflow: hidden;
    }
    .triangle-up div {
        width: 0;
        height: 0;
        margin-left:-500px;
        border-left: 500px solid transparent;
        border-right: 500px solid transparent;
        border-bottom: 500px solid green;
    }
    

    Or using pseudoelements and just one div:

    .triangle-up {
        width: 50%;
        height: 0;    
        padding-left:50%;
        padding-bottom: 50%;
        overflow: hidden;
    }
    .triangle-up:after {
        content: "";
        display: block;
        width: 0;
        height: 0;
        margin-left:-500px;
        border-left: 500px solid transparent;
        border-right: 500px solid transparent;
        border-bottom: 500px solid #959595;
    }
    

    Here's a fiddle. For the full explanation on how these work and the down, left and right pointing triangle snippets see my article on Pure CSS responsive triangles. The CSS given is for a triangle with base-height ratio of 2. Trying to change the triangle's proportions without knowing how these triangles fake responsiveness may be complicated.

提交回复
热议问题