CSS implements triangles, div implements triangle gaps

1. CSS to implement triangles

Sometimes in interview questions or daily needs, there will be examples of using pure CSS to implement triangles. Currently, I can only provide two solutions based on my knowledge.

The first is the first and most commonly used method is the border method.

1-1 border implementation triangle

div{
      border:40px solid;
      border-left-color: lightslategrey;
      border-right-color: lightcoral;
      border-top-color: lawngreen;
      border-bottom-color: lightgreen;
      box-sizing: border-box;
      width: 40px;
}            

The effect is as follows. If you want a triangle in a certain direction, just set the color of other angles to transparent.

For example, I only want pink triangles

/*顺序分别是上右下左*/
border-color: transparent lightcoral transparent transparent;

 

1-2 Implement triangles through linear-gradient()

div{
  width: 50px;
  height: 50px;
  background: linear-gradient(-45deg, red 50%, transparent 50% ) ;
}

The renderings are as follows:

So let’s briefly introduce that  linear-gradient()  is the gradient function of background in CSS.

Its first parameter refers to your starting angle. For the angle diagram, I found a diagram from the Internet. -45deg means from the lower right corner to the upper left corner, and 135deg means from the upper left corner to the lower right corner. You can also specify the direction directly. (left/right/top/bottom to left/right/top/bottom)

The second parameter is to specify the color. Generally, it must be multiple colors, because to achieve a gradient effect, the last 50% can be written or not. If written, it means that red accounts for 50%. The emphasis is here! ! If the percentage in your second parameter is greater than or equal to the percentage of the second parameter, there will be no gradient, for example

  {
    background: linear-gradient(-45deg, red 50%, blue 50% ) ;
  }    

Because each element occupies 50%=50%, there is no gradient effect in the middle, but!

​
  {
    background: linear-gradient(-45deg, red 20%, blue 50% ) ;
  }    

​

There will be a gradient

2. To achieve missing corners in div, use the third method

 width: 200px;
 height: 50px;
 background: linear-gradient(-45deg, transparent 20px, blue 0 ) ;

Guess you like

Origin blog.csdn.net/wuguidian1114/article/details/105736077