How to make a pure css triangle which has a white center

前端 未结 4 1025
囚心锁ツ
囚心锁ツ 2021-02-20 17:45

I want to create an upward and downward facing arrow with css like the following: http://apps.eky.hk/css-triangle-generator/

However, instead of a solid color, I want to

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-20 18:32

    To create triangles with only CSS we use a zero width/height element with borders:

    .arrow-up {
        width  : 0;
        height : 0;
    
        border-left   : 50px solid transparent;
        border-right  : 50px solid transparent;
        border-bottom : 50px solid black;
    }
    

    Since we are using borders to create the arrow, we can't just give it a border, but we can overlay one arrow on top of a slightly larger arrow to make the appearance of a border:

    HTML --

    CSS --

    .top {
        position : absolute;
        top      : 6px;
        left     : 10px;
        width    : 0;
        height   : 0;
        z-index  : 100;
        
        border-left   : 50px solid transparent;
        border-right  : 50px solid transparent;
        border-bottom : 50px solid black;
    }
    .bottom {
        position : absolute;
        width    : 0;
        height   : 0;
        z-index  : 99;
        
        border-left   : 60px solid transparent;
        border-right  : 60px solid transparent;
        border-bottom : 60px solid red;
    }​
    

    Here is a demo: http://jsfiddle.net/jasper/qnmpb/1/

    Update

    You can then put both of the triangle DIV elements inside a container and move that container however you want:

    HTML --

    CSS --​

    #container {
        position : relative;
        top      : 25px;
        left     : 25px;
    }
    

    Here is a demo: http://jsfiddle.net/jasper/qnmpb/3/

    EDIT (2014):

    I just came back to this answer and noticed that separate HTML elements are not necessary to create your double-triangle. You can use pseudo-elements, :before and :after. I.e. replace the .top selector with something like .my-element-that-needs-a-triangle:before and the .bottom selector with something like .my-element-that-needs-a-triangle:after.

提交回复
热议问题