CSS Triangle, CSS Shapes

By Xah Lee. Date: . Last updated: .

This page shows you how to use pure CSS to create a triangle, circle, and other shapes.

Here's a CSS triangle.

here's the HTML code:

<div class="xyz"></div>

here's the CSS code:

div.xyz {
width: 0; height: 0;
 border-left: 20px solid red;
 border-right: 20px solid transparent;
 border-top: 20px solid transparent;
 border-bottom: 20px solid transparent;
}

The trick is to set the element to have 0 width and height, then use a thick border, then make the sides of border transparent except one side.

Here's the same element but with border sides colored, and the element has width height of 10 px, and with text “A”.

A

CSS triangle can save you from using a image, which is slower because of HTTP request.

CSS Shapes

The border, border radius, and opacity, and CSS transformation can be combined to create many different shapes.

Here's a example of pacman.

Here's the CSS code:

div.pacman46958 {
width:0;
height:0;
line-height:0;
border:20px solid red;
border-radius:20px;
border-left:20px solid transparent;
}

Basically, you set a thick border, make the corners round, then set one side of border to be transparent, and also set width and height to be 0 so there's no hole in the middle.

〔►see CSS: Round Corners, border-radius

Using Unicode for Triangle and Shapes

A even better solution is to use Unicode. Here's a example:

Here's the HTML code:

<p><span class="unicode-triangle-87339"></span></p>

Here's the CSS:

span.unicode-triangle-87339 {font-size:40px;color:red}

Best to set your HTML to use UTF-8 encoding. See: Character Sets and Encoding in HTML.

For more Unicode shapes, see:

Using 2D Transform and SVG for Shapes

You can use CSS3 2D Transform to create much more shapes. See: CSS: 2D Transform.

The most general way to create arbitrary shapes is SVG. See:

CSS Effects

  1. CSS: Round Corners, border-radius
  2. CSS: Box Shadow
  3. CSS: Text Shadow/Outline
  4. CSS Triangle, CSS Shapes
  5. CSS: 2D Transform
  6. CSS: Image Rollover
  7. CSS: Background Image, CSS Sprites Tutorial
  8. CSS: Transition Tutorial
  9. CSS: Animation Tutorial
Like what you read? Buy JavaScript in Depth