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

如何使用CSS实现矩形盒子的自指向箭头效果

实现方案

你可以通过CSS伪元素+边框三角形的方案实现指向自身的箭头效果,以下是完整可运行的代码:

完整代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>盒子自身箭头效果</title>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    body {
      margin: 10px;
    }
    .wrapper {
      display: flex;
      gap: 20px;
      align-items: flex-start;
    }
    .container {
      height: 200px;
      width: 200px;
      border: 1px solid black;
      position: relative;
      background: #fff;
    }
    /* 箭头样式:示例为从右侧指向盒子内部的箭头 */
    .container::before {
      content: '';
      position: absolute;
      /* 定位到盒子右侧边缘,可调整top/right/left/bottom的值修改箭头位置 */
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      /* 边框生成三角形 */
      width: 0;
      height: 0;
      border-top: 10px solid transparent;
      border-bottom: 10px solid transparent;
      border-right: 10px solid black;
    }
    .container::after {
      content: '';
      position: absolute;
      right: 1px;
      top: 50%;
      transform: translateY(-50%);
      width: 0;
      height: 0;
      border-top: 9px solid transparent;
      border-bottom: 9px solid transparent;
      border-right: 9px solid #fff;
    }
    .container-2 {
      margin-top: 4em;
      height: 75px;
      width: 75px;
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="container"></div>
    <div class="container-2"></div>
  </div>
</body>
</html>

实现说明

  • 用两个伪元素叠加实现带边框的箭头效果:::before做箭头的外边框,::after做箭头的内部填充,遮盖住多余的边框部分
  • 调整伪元素的top/right/left/bottom属性,即可修改箭头在盒子四周的位置;修改边框的颜色赋值方向,即可调整箭头的朝向,比如要生成左侧指向内部的箭头,就把border-right换成border-left,同时把定位逻辑调整到盒子左侧边缘即可
  • 三角形的大小可以通过调整边框的宽度值自定义修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:57:03