CSS 绘制图形

156 阅读2分钟

最近在面试中遇到了一个经常问到的css面试题,如何使用 css 实现一个三角形。今天我们就来总结一下 css 绘制三角形的几种方法,同时使用 css 绘制一些其他的图形。

css 画三角形

  1. border 实现
.triangle {
  width: 0;
  height: 0;
  border: 100px solid transparent;
  border-bottom: 200px solid #0ff;
}
  1. 使用 linear-gradient 绘制三角形
.triangle {
  background: linear-gradient(
    45deg,
    deeppink,
    deeppink 50%,
    transparent 50%,
    transparent 1px
  );
  transform: rotate(135deg);
}
  1. 使用 conic-gradient 绘制三角形
.triangle {
  background: conic-gradient(
    from 90deg at 50% 0,
    deeppink 0,
    deeppink 45deg,
    transparent 45.1deg
  );
}
  1. transform 配合 overflow 实现
.triangle {
  position: relative;
  background: unset;
  overflow: hidden;
}

.trangle::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: deeppink;
  transform-origin: left bottom;
  transform: rotate(45deg);
  z-index: -1;
}
  1. clip-path
.trangle {
  background: deeppink;
  clip-path: polygon(0 0, 100% 0, 0 100%, 0 0);
}
  1. 使用字符
◄ : ◄
► : ►
▼ : ▼
▲ : ▲
⊿ : ⊿
△ : △
<div class="normal">&#9660; </div>

div {
    font-size: 100px;
    color: deeppink;
}

css 绘制六角星

使用两个三角形叠在一起就可以实现六角星的效果

<div class="icon star"></div>
.icon {
  display: inline-block;
  width: 0;
  font-size: 0;
  position: relative; 
  margin-right: 20px;
}

.star {
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}

.star::after {
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 100px solid red;
  position: absolute;
  content: "";
  top: 30px; left: -50px;
}

css画箭头图形

箭头左侧加一个三角形遮挡,右侧加一个三角形来画箭头

<div class="icon arrow"></div>

.icon {
  display: inline-block;
  width: 0;
  font-size: 0;
  position: relative; 
  margin-right: 20px;
}
.arrow {
  width: 40px;
  height: 40px;
  margin: 0 40px;
  background-color: red;
}

.arrow::before {
  position: absolute;
  left: -40px;
  border: solid 20px red;
  border-left-color: transparent;
  content: "";
}

.arrow::after {
  position: absolute;
  right: -40px;
  border: solid 20px transparent;
  border-left-color: red;
  content: "";
}


css画吃豆人

<div class="icon pacman"></div>
.icon {
  display: inline-block;
  width: 0;
  font-size: 0;
  position: relative; 
  margin-right: 20px;
}
.pacman {
  width: 0px; height: 0px;
  border-right: 40px solid transparent;
  border-top: 40px solid red;
  border-left: 40px solid red;
  border-bottom: 40px solid red;
  border-top-left-radius: 40px;
  border-top-right-radius: 40px;
  border-bottom-left-radius: 40px;
  border-bottom-right-radius: 40px;
}

总结

CSS 可以绘制很多种图形,按照 HTML、CSS、JS各司其职的原则,我们应该在开发中尽量使用 HTML 和 CSS 来控制样式的变化,而使用 JS 来实现业务逻辑和其他的功能。