Search code examples
cssshapescss-shapes

Mechanics behind the CSS shape


http://jsfiddle.net/zth05v3q/

div {
    background:red;
    width:100px;
    height:100px;

}
div:after{
      content: '';
      position: absolute;
      display: block;
      border: 40px solid green;
      border-left-width: 15px;
      border-right-width:15px;
      border-left-color: transparent;
}

I've created this shape many times but I don't quite get how the shape comes about to be by just adjusting left and right border widths, need an explanation so I understand what I'm doing.

A picture of the shape


Solution

  • Actually, this is rather easy to explain if you think about it.

    So, let's start with the basics. How exactly are borders rendered?

    First, let's look at a normal border (border: 10px solid black; background: green):

    Regular border

    Looks just like you'd expect. Now, let's look at it with different colors all around:

    Different colored borders

    As you can see, the borders are drawn evenly, and at an angle where they join.

    The one in your example has border: 40px solid green;. This means that the entire border is 40px wide and green. To emphasize, here's a shape with exaggerated borders. The width and height are 0, so this is all borders:

    Exaggerated Borders

    At this point, if we make the left border transparent, it will just be green (in my example), or red (in your example).

    So, let's do that, then (A) stretch it a bit (make the borders on top and bottom be a bit bigger than the left and right ones).

    After that, (B) have the top, right, and bottom borders the same color.

    Then, finally, we'll (C) (I also resized it to match your picture), throw it inside of another div. (Basically, the :after tag means place this thing inside the current container, but at the end of it).

    Final Results

    So, there you have it. Borders in a nutshell.

    Example fiddle showing each step.