用 CSS 做一个三角形

96 阅读1分钟

用 CSS 做一个三角形

实现原理: 利用盒子边框完成

实现步骤:1. 设置一个盒子,将盒子宽高设置为0,仅保留边框
font-size和line-height可以不加,但是在以前的浏览器IE6版本以下呢会有一个默认大小

div{
 /* 固定的 */
      width: 0;
      height: 0;
      font-size: 0;
      line-height: 0;
}
  1. 设置四周不同颜色的边框
div{
        border-top: 100px solid transparent;
        border-bottom: 100px solid green;
        border-left: 100px solid transparent;
        border-right: 100px solid transparent;
}

正方形.png
3. 得到四个三角形,选择其中一个后,其他三角形(边框)设置颜色为透明

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style>
    div {
      /* 固定的 */
      width: 0;
      height: 0;
      font-size: 0;
      line-height: 0;

      border-top: 100px solid transparent;
      border-bottom: 100px solid rgb(0, 255, 221);
      border-left: 100px solid transparent;
      border-right: 100px solid transparent;


    }
  </style>
</head>

<body>
  <div></div>
</body>

</html>

三角形.png
简单的写法一:设置一个统一的边框,颜色直接设置成透明色,想要生成尖尖向右的三角形就改变left边框的颜色

border: 100px solid transparent;
border-left: 100px solid rgb(255, 0, 212);

右三角形.png
简单的写法二:

border: 100px solid transparent;
border-left-color: rgb(255, 0, 212);

一个新鲜的三角形就出炉啦🥳🥳