Wednesday, June 29, 2011

Making Triangles in CSS

Making triangles in CSS is quite useful, and simple to do using basic border techniques.

You've probably seen CSS triangles used for drop down menus, where the triangle points up or down based on the state of the menu.

 First, let's start with a basic grey square that is 20 pixels wide:
<html>
<head>
<style type="text/css">
  .square {
    width: 20px;
    height: 20px;
    background-color: silver;
  }
</style>
</head>
<body>
  <div class="square"></div>
</body>
</html>

Next we'll add a 20 pixel border on all sides, making the square 60 pixels wide with its borders:
<html>
<head>
<style type="text/css">
  .square {
    width: 20px;
    height: 20px;
    background-color: silver; 
    border: 20px solid red;
  }
</style>
</head>
<body>
  <div class="square"></div>
</body>
</html>

Let's take a closer look at the borders individually by assigning each one a different color:
<html>
<head>
<style type="text/css">
  .square {
    width: 20px;
    height: 20px;
    background-color: silver; 
    border: 20px solid;
    border-top-color: orange;
    border-left-color: blue;
    border-right-color: green;
    border-bottom-color: red;
  }
</style>
</head>
<body>
  <div class="square"></div>
</body>
</html>

Now you may notice that if we reduced the grey portion of the square we could bring these borders together and they would each form their own triangle. We do this by reducing the size of the square to 0 pixels:
<html>
<head>
<style type="text/css">
  .square {
    width: 0px;
    height: 0px;
    border: 20px solid;
    border-top-color: orange;
    border-left-color: blue;
    border-right-color: green;
    border-bottom-color: red;
  }
</style>
</head>
<body>
  <div class="square"></div>
</body>
</html>

And now to isolate any one of the triangles, we can just set the opposite border to 0 pixels, and the adjacent borders to transparent:
<html>
<head>
<style type="text/css">
  .square {
    width: 0px;
    height: 0px;
    border: 20px solid;
    border-top-color: orange;
    border-left-color: transparent;
    border-right-color: transparent;
    border-bottom: 0px;
  }
</style>
</head>
<body>
  <div class="square"></div>
</body>
</html>

We now have a 20 pixel tall, 40 pixel wide triangle. The triangle can be resized and transformed by changing the border widths.