Friday, 8 April 2011

CSS: create shapes in pure css

   


It's been a long time ago that I first heard about creating shapes with pure CSS. Now things are evolving - as I've already explained in quite a few posts lately. Again, compatibility is like a proverbial sword, hanging on our heads, however, if we feel like experimenting, this article can actually be a good place.
I am going to show you how to create shapes in CSS. As said, nothing really new.

Simple shapes
Let's start with very simple shapes.

.square {
width: 100px;
height: 100px;
background: blue; }




.circle {
width: 100px;
height: 100px;
background: blue;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px; }


.triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid blue; }
In order to change the triangle position, you can play with border-right, left, top and bottom, according to your needs. Removing one border, you can achieve different effects:


.triangle-topleft {
width: 0;
height: 0;
border-top: 100px solid blue;
border-right: 100px solid transparent; }

Using CSS3 transform, we can apply skews and obtain a parallelogram:

.parallelogram {
width: 150px;
height: 100px;
-webkit-transform: skew(10deg);
-moz-transform: skew(10deg);
-o-transform: skew(10deg);
background: blue; }

Or a trapezoid...

.trapezoid {
border-bottom: 100px solid blue;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
height: 0;
width: 100px; }
Complex shapes
How about a star?



.star-six {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid blue;
position: relative; }

.star-six:after {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 100px solid blue;
position: absolute;
content: "";
top: 30px;
left: -50px; }

Basically here we take advantage of CSS pseudo-elements, and specifically :after. Following that idea, and using the :before pseudo element, we can create almost any kind of shape.




.pentagon {
position: relative;
width: 54px;
border-width: 50px 18px 0;
border-style: solid;
border-color: blue transparent; }

.pentagon:before {
content: "";
position: absolute;
height: 0;
width: 0;
top: -85px;
left: -18px;
border-width: 0 45px 35px;
border-style: solid;
border-color: transparent transparent blue; }

More complicated shapes can be create (like octagons or even hearts and infinite loop simbols), however in my opinion they might be only exercises with little day-to-day use.
Anyway, I hope you might have been inspired by the above examples and find it useful.

Please let me know what you think.

3 comments:

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.