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

如何用CSS在正方形顶部创建三角形?(附现有代码求助)

实现顶部带三角形的正方形

顶部带三角形的正方形

你当前的代码已经搭建了基础形状,但伪元素未设置定位导致无法显示在正确位置,以下是可行的解决思路和修改后的代码:

核心问题分析

你写的三角形伪元素默认是静态定位,不会脱离文档流,因此无法显示在正方形上方;同时需要让三角形与正方形的外框精准对齐。

解决步骤

  • 给正方形容器添加position: relative,为伪元素提供定位基准
  • 给三角形伪元素设置绝对定位,通过left: 50% + transform: translateX(-50%)实现水平居中
  • 调整伪元素的top值,让三角形正好衔接正方形的外框顶部
  • 保持外框样式(outline或border)的一致性

修改后的代码

CSS

.square {
  width: 20px;
  height: 20px;
  background: #FF0000;
  outline: 1px solid #000;
  outline-offset: 4px;
  position: relative; /* 为伪元素提供定位基准 */
}

.arrow::before {
  content: '';
  position: absolute;
  top: -9px; /* 计算逻辑:outline偏移量(4px) + 三角形高度(5px),取负值让它到容器上方 */
  left: 50%;
  transform: translateX(-50%); /* 实现水平居中 */
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 5px solid #000;
}

HTML

<div class='square arrow'></div>

替代方案(用border+padding实现外框)

如果觉得outline的定位计算麻烦,也可以用border+padding替代outline,定位逻辑更直观:

.square {
  width: 20px;
  height: 20px;
  background: #FF0000;
  border: 1px solid #000;
  padding: 4px;
  position: relative;
  box-sizing: border-box; /* 确保padding不影响容器整体尺寸 */
}

.arrow::before {
  content: '';
  position: absolute;
  top: -6px; /* 计算逻辑:border宽度(1px) + 三角形高度(5px),取负值 */
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 5px solid #000;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:06:13