你真的了解css绘制三角形吗?

原理

先上口诀:宽高为0,一边为0,两边透明。

元素的border的形成机制是:

在盒子四边由4个三角形 拼接而成,最先呈现的是每个三角形底部的内容,当border-width变大后,每个三角形的剩余部分会渐渐出现;

当盒子内容有宽高时,会遮住每个三角形底部之外的部分;

比如

css 复制代码
width: 40px;
height: 40px;
border-width: 50px;
border-style: solid;
border-color: red yellow green blue;

当border-width设置过小时,就是平时的场景(只看到每个三角形底部区域):

css 复制代码
width: 40px;
height: 40px;
border-width: 1px;
border-style: solid;
border-color: red yellow green blue;

当盒子宽高设置为0后,每个三角形全部呈现:

css 复制代码
width: 0;
height: 0;
border-width: 30px;
border-style: solid;
border-color: red yellow green blue;

如果有一边不设置border-width,就只有三个三角形:

css 复制代码
width: 0;
height: 0;
border-width: 30px 30px 30px 0;
border-style: solid;
border-color: red yellow green #fff;

如果将上下两边的color设置为透明,不就是只看到一个三角形吗:

css 复制代码
width: 0;
height: 0;
border-width: 30px 30px 30px 0;
border-style: solid;
border-color: transparent yellow transparent #fff;

不难发现,不设置border-width那一边就是三角形的方向,三角形方向的方向的邻近两边需要设置透明。

实现口诀:宽高为0,一边为0,两边透明

css 复制代码
width: 0;
height: 0;
border-width: 30px 30px 30px 0;
border-style: solid;
border-color: transparent yellow transparent #fff;
相关推荐
htzyl2061 天前
前端样式-弹窗淡入淡出,为什么你的 `transition` 一直不生效
前端·css·html
Brookty1 天前
CSS基础知识(二):盒模型、内外边距、外边距折叠与父子元素的布局关系
前端·css
Mh2 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
Brookty2 天前
CSS基础知识(一):选择器、优先级、层叠与继承、边框属性及盒模型
前端·css
htzyl2062 天前
CSS中,`:has()` 能帮你删掉的 4 类 JS
前端·css
jianqiang.xue3 天前
Espressif-IDE进入维护模式:乐鑫把ESP32开发的宝押给VS Code
前端·css·ide
feixing_fx3 天前
CSS 变量(Custom Properties):构建可扩展的主题切换系统
前端·css·前端框架·html·css3
晓得迷路了5 天前
栗子前端技术周刊第 154 期 - Parcel 3 Alpha、JS 调查报告、Vite 漏洞...
前端·javascript·css
ZhengEnCi6 天前
登录页电脑端怎么设计才不空:5 种布局方案与可粘贴 AI 提示词
前端·css·设计
神膘护体小月半7 天前
css - 元素背景图由 hover 触发,初次加载时闪动的解决办法
前端·javascript·css