Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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 set it up so the inside is white and there is just a border around the triangle. (So the triangle would be multi-colored, one color on the inside and a different colored border).

Is this possible, and if so, how can it be done?

like image 456
Evan Avatar asked Feb 28 '12 20:02

Evan


1 Answers

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 --

<div class="top"></div>
<div class="bottom"></div>​

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 --

<div id="container">
    <div class="top"></div>
    <div class="bottom"></div>
</div>

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.

like image 125
Jasper Avatar answered Oct 16 '22 21:10

Jasper