You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tailwind CSS创建带三角侧边的矩形与八边形形状?

使用Tailwind CSS创建带三角侧边的矩形和八边形

一、带三角侧边的矩形

可以通过相对定位主容器 + 伪元素/子元素三角形实现,同时保留你需要的白色边框效果,解决你之前不对称的问题:

实现代码(子元素写法,更直观)

<div className="relative w-28 h-7 m-1 flex justify-center items-center bg-[#6666ff] border border-white">
  {/* 右侧三角 */}
  <div className="absolute right-0 top-0 h-full w-0 border-l-[8px] border-l-[#6666ff] border-y-[14px] border-y-white -translate-x-[1px]"></div>
</div>

关键说明

  • 主容器用relative定位,方便三角元素对齐
  • 三角形通过边框技巧实现:主容器高度为h-7(28px),所以设置border-y-[14px](高度一半)保证上下对称,border-l-[8px]控制三角宽度
  • -translate-x-[1px]抵消主容器的白色边框宽度,避免出现缝隙

如果习惯用伪元素写法,可直接用Tailwind的after:前缀:

<div className="relative w-28 h-7 m-1 flex justify-center items-center bg-[#6666ff] border border-white after:content-[''] after:absolute after:right-0 after:top-0 after:h-full after:w-0 after:border-l-[8px] after:border-l-[#6666ff] after:border-y-[14px] after:border-y-white after:-translate-x-[1px]"></div>

二、八边形

推荐两种实现方式,按需选择:

方法1:clip-path(简洁推荐)

Tailwind支持自定义clip-path,通过配置工具类快速实现:

<div className="w-28 h-28 m-1 bg-[#6666ff] border border-white clip-path-octagon"></div>

需要在tailwind.config.js中添加自定义工具类:

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    extend: {
      clipPath: {
        octagon: 'polygon(20% 0%, 80% 0%, 100% 20%, 100% 80%, 80% 100%, 20% 100%, 0% 80%, 0% 20%)',
      },
    },
  },
  plugins: [],
}

调整polygon里的百分比可以改变切角大小,数值越小切角越不明显。

方法2:伪元素叠加(无需配置)

通过四个角的伪元素模拟切角,无需修改Tailwind配置:

<div className="relative w-28 h-28 m-1 bg-[#6666ff]">
  <div className="absolute inset-0 m-[6px] bg-[#6666ff] border border-white"></div>
  {/* 左上角切角 */}
  <div className="absolute top-0 left-0 w-6 h-6 border-b-[6px] border-b-white border-r-[6px] border-r-white"></div>
  {/* 右上角切角 */}
  <div className="absolute top-0 right-0 w-6 h-6 border-b-[6px] border-b-white border-l-[6px] border-l-white"></div>
  {/* 左下角切角 */}
  <div className="absolute bottom-0 left-0 w-6 h-6 border-t-[6px] border-t-white border-r-[6px] border-r-white"></div>
  {/* 右下角切角 */}
  <div className="absolute bottom-0 right-0 w-6 h-6 border-t-[6px] border-t-white border-l-[6px] border-l-white"></div>
</div>

修改w-6/h-6和边框数值可以调整切角大小。


内容的提问来源于stack exchange,提问作者peakyBlinders

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:28:00