“CSS箭头”如何运作?

时间:2015-09-30 23:58:04

标签: css

我见过几个“CSS箭头”的例子 - 基本上是一个箭头/三角形,用纯CSS完成。这里的例子:

......等等。

然而,无论我对它们进行多少调查,我都不知道它是如何工作的以及为什么会产生箭头。

采用这个小例子,改编自第一个链接:

.arrow-up {
	width: 0; 
	height: 0; 
	border-left: 50px solid transparent;
	border-right: 50px solid transparent;
	
	border-bottom: 50px solid black;
}
<div class="arrow-up"></div>

为什么透明的左右边框会产生向上箭头?发生了什么事?

1 个答案:

答案 0 :(得分:8)

如何在0x0平方左右绘制50px边框?

制作100x100平方。

#########
#########
#########
#########
#########

但是,你如何独立控制所有四条边?

将正方形切成4个三角形。每个三角形都是一个完整的边框,但由于边框厚度为50px,它实际上由四个不同的实心边框组成:

  #########
#   #####   #
###   #   ###
####     ####
###   #   ###
#   #####   #
  #########

现在,将顶部,左侧和右侧三角形透明,然后只留下底部边框,形成向上三角形。

      #    
    #####   
  #########

你留下一个向上的三角形,底边的颜色。

这是一个使用越来越大的边框宽度的演示:

div {
  margin: 10px;
}

#one {
  width: 90px;
  height: 90px;
    
  border-top: 5px solid blue;
  border-left: 5px solid red;
  border-right: 5px solid green;
  border-bottom: 5px solid black;
}

#two {
  width: 50px;
  height: 50px;
    
  border-top: 25px solid blue;
  border-left: 25px solid red;
  border-right: 25px solid green;
  border-bottom: 25px solid black;
}


#three {
  width: 0;
  height: 0;
    
  border-top: 50px solid blue;
  border-left: 50px solid red;
  border-right: 50px solid green;
  border-bottom: 50px solid black;
}


#four {
  width: 0;
  height: 0;
    
  border-top: 50px solid transparent;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 50px solid black;
}
<p>First, lets make a box, 100x100px. We'll use a 5px border, and a 90x90px content area.</p>
  
<div id="one"></div>

<p>Next, lets make the box smaller, but make the borders bigger. You should start to see how the four borders are controlled independly. We'll use a 50x50px box and a 25px border.</p>
  
<div id="two"></div>

<p>Now we'll shrink the box down to 0x0, with a 50px border on all edges. Now, there is no box, only border. It's now quite obvious that, as the border grows and the content shrinks, the border is cut along the corners at a 45 degree angle.</p>

<div id="three"></div>

<p>Finally, if we make the top, left and right borders transparent, ony the lower triangle making up the bottom border is left.</p>

<div id="four"></div>