Making simple shapes with HTML and CSS

In web development, HTML is for laying out content such as text and images, while CSS is for visually styling the content defined in the HTML.

For the web, it used to be the case that if you wanted to bring in any sort of imagery, you had to create it first in Photoshop. Not just photos, but even basic illustrations such as shapes.

But today, it’s actually possible to create shapes and a whole lot more, right on the web. Take a look here at a square and circle. They were coded with HTML and CSS.

Here is the code used to create them. You can see that it’s rather simple.

<!-- define a square -->
<div class="square"></div>
<!-- define a circle -->
<div class="circle"></div>
div.square {
	width: 120px;
	height: 120px;
	background-color: darkcyan;
} {
	width: 120px;
	height: 120px;
	border-radius: 50%;
	background-color: tomato;

The HTML <div> tag is used to define a region on a webpage. The size of the region is determined by the width and height dimensions in the CSS.

To make this a square shape, we simply fill the space with a color (background-color). To make this a rectangle, just make the width different from the height.

For a circle, we add one extra step, by incorporating border-radius to round the 4 corners of the square. If you set the radius to 50 percent of the size of the square, you end up with a circle.

To create an oval, apply the same 50 percent border radius to a rectangle.


Can you create a triangle? Yes, certainly!


The underlying CSS is interesting.

<div class="triangle-up"></div>

<div class="triangle-right"></div>
div.triangle-up {
	width: 0;
	height: 0;
	border-left: 60px solid transparent;
	border-right: 60px solid transparent;
	border-bottom: 120px solid indigo;

div.triangle-right {
	width: 0;
	height: 0;
	border-top: 60px solid transparent;
	border-left: 120px solid lightseagreen;
	border-bottom: 60px solid transparent;

At first, it’s not easy to intuitively grasp what’s happening in the CSS. Creating the triangle shape involves some CSS trickery, a play on the use of borders.

Basically, you designate a border with a size that sets the width of the base of the triangle, and a color that “fills” the triangle. Then, define the two surrounding borders at half the size and make them transparent. When all three borders are combined, you get the shape of a triangle.

There are, of course, many other shapes you can create with CSS. You can get more creative and make some interesting visual objects, too. And, there are several web development tools ideal for making artwork and illustrations, including SVG, the Canvas API, and most recently, the CSS Paint API.