css Triangles, etc.

1. A 100px div with 50px borders (= 200px per side). All four sides have different border-color values. Note the mitered corners where the borders meet.

2. Here the div has width:0 and height:0, but border-width:100px, to make a solid, 200px square that is all border.

3. A basic css triangle: making the border-left and -right transparent leaves us with a css triangle. The border-top value can be left out completely.

4. An acute triangle: giving the left and right borders unequal widths pushes the vertex left or right:
border-left-width:30px; border-right-width:170px; note that the widths add up to 200px.

5. An equilateral triangle: Increasing the border-bottom-width changes the height of the triangle. Here it is 173px (from the formula for the height of a triangle [100px × √3]) to make an equilateral triangle.

6. A right triangle:
border-right-width:0, border-left-width:200px, border-bottom-width:100px.
 

7. A trapezoid: The div now has width:100px, height:0, and border-left and border-right-widths of 50px; border-bottom-width is 100px.

8. A trapezium: div width:100px,
and unequal border-left and border-right-widths totaling 200px; border-bottom-width is 100px.

9. A rhombus: Two similar triangles side-by-side. Here the border-top and -bottom-colors are transparent, and the left and right are defined.

CSS TRIANGLES CAN BE TRICKY to wrap your mind around, but the idea is really pretty simple.

Most HTML elements are essentially rectangles. Yes, we can make circles and ellipses with border-radius, but that merely disguises the fact that they have four sides: top, right, bottom, and left. If we could define separate length values for each of the sides, it would be easy to make triangles (and many other shapes) simply by giving one side a length of 0. Since that is not possible, we have to think outside of the box, literally, and look at the border property instead.

If you give a block HTML element a reasonably large border-width and give each side a different border-color, you will see a diagonal miter that occurs at the corners where the borders meet. This diagonal line is the key to making CSS triangles.

The basic idea is to define a visible border-color for only one side of the element, and to give the two adjacent sides a border-color:transparent; the opposite side border does not need to be defined at all. By adjusting the border-widths of those three sides and giving the element width:0 and height:0, you can make any kind of triangle. See the examples above for more details.

The defect of this method is that the triangles are not containers: you can’t easily place text or images inside a CSS triangle since it is only a border. You could fake it with pseudo-elements and absolute positioning, though.