Mechanics behind 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 have created this shape many times, but I don't quite understand how the shape is formed, just adjusting the width of the left and right border, needs an explanation, so I understand what I am doing.

A picture of the shape

+3


source to share


2 answers


It's actually pretty easy to explain if you think about it.

So let's start with the basics. How are borders displayed accurately?

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

Regular border

Sounds like you expected. Now let's look at it in different colors:

Different colored borders

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

Your example has border: 40px solid green;

. This means the entire border is 40px wide and green. Let's emphasize here a form with exaggerated borders. Width and height are 0, so all borders are:



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 this, then (A) stretch it out a bit (make the top and bottom borders slightly larger than the left and right).

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

Then finally we will (C) (I also resized it to fit your image), throw it in another div. (Basically, after the tag means placing this thing inside the current container, but at the end of it).

Final Results

So this is it. Borders in a nutshell.

An example script showing each step.

+6


source


Your code creates a pseudo-block element with a width and height of 0. In this 0 pixel by 0 pixel block, you add borders.

The corner of the CSS border is at an angle to two adjacent sides. Each edge of the border is usually trapezoidal. In this case, the inner edge is 0 pixels wide, which creates a triangle at each dimension.

By controlling the width of each dimension, you can change the height of the 4th triangle created around the edge. Also, by setting the side color to transparent or another color, you can get a triangular cut in the shape.

To visualize what is happening, check what happens when the width and height are added to the pseudo-element and each side of the border has a different color.



Example

border-top-color: blue;
border-bottom-color: yellow;
width: 10px;
height: 10px;

      

enter image description here

+2


source







All Articles