Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can this CSS snippet draw a triangle? [duplicate]

Tags:

css

css-shapes

I saw the following code without any comments..

.triangle {
    border-color: transparent;
    border-bottom-color: green;
    border-style: solid;
    border-width:  300px;
    border-top-width:0;
    height: 0;
    width: 0
}
<div class="triangle"></div>

The result is a green triangle. Does anyone have ideas about why it works?

like image 501
Hanfei Sun Avatar asked Nov 11 '15 12:11

Hanfei Sun


1 Answers

Corners of a border meet at 45 degree angles.

So showing only one border will show the tapered edges where one side meets the next.

By making 3 of the borders invisible or the same colour as the background we get the illusion of a triangle.

.bdr1{
  height:100px;
  width:100px;
  display:block;
  border:25px solid;
  border-color:red blue green black;
 }
.bdr2{
  height:0;
  width:0;
  display:block;
  border:100px solid;
  border-color:red blue green black;
 }
.bdr3{
  height:0;
  width:0;
  display:block;
  border:100px solid;
  border-color:red white white white;
 }
<div class="bdr1"></div><br/>
<div class="bdr2"></div><br/>
<div class="bdr3"></div>

SHAPING THE FUTURE

This technique creates an excellent way to create even more elaborate shapes using only css.

STAR

.Star{ 
  width: 0; 
  height: 0; 
  border-left: 50px solid transparent; 
  border-right: 50px solid transparent; 
  border-bottom: 100px solid red; 
  position: relative; 
} 
.Star:after { 
  width: 0; height: 0; 
  border-left: 50px solid transparent; 
  border-right: 50px solid transparent; 
  border-top: 100px solid red;
  position: absolute; content: ""; 
  top: 30px; 
  left: -50px; 
}
<div class="Star"></div>

CHEVRON

.Chevron{
    position:relative;
    display:block;
    height:50px;/*height should be double border*/
}
.Chevron:before,
.Chevron:after{
    position:absolute;
    display:block;
    content:"";
    border:25px solid transparent;/*adjust size*/
}
/*Change four 'top' values below to rotate (top/right/bottom/left)*/
.Chevron:before{
    top:0;
    border-top-color:#b00;/*Chevron Color*/
}
.Chevron:after{
    top:-10px;/*adjust thickness*/
    border-top-color:#fff;/*Match background colour*/
}
<i class="Chevron"></i>
like image 164
DreamTeK Avatar answered Nov 09 '22 12:11

DreamTeK