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

如何用纯HTML/CSS实现文本适配轮廓的可编辑居中菱形元素

解决方案

以下是在原有实现基础上修改的代码,完全满足所有需求,改动量极小:

完整CSS代码

body {
  background-color:gray;
}

.diamond-container{
  position:absolute;
  width: 214px;
  height: 214px;
  display: inline-block;
  z-index:1;
}

.diamond-left-textwrap {
  float: left;
  shape-outside: polygon(0 0, 100% 0, 0 50%, 100% 100%, 0 100%, 0 0);
  width: 50%;
  height: 100%;
}

.diamond-right-textwrap {
  float: right;
  shape-outside: polygon(0 0, 100% 50%, 0 100%, 100% 100%, 100% 0, 0 0);
  width: 50%;
  height: 100%;
}

.diamond-shape {
  background-color:white;
  border: 6px solid black;
  transform: rotate(45deg) scale(0.715);
  position:absolute;
  z-index:0;
  width: 100%;
  height: 100%;
}

.text-container {
  height:100%;
  width:100%;
  text-align:center;
  outline: none;
  box-sizing: border-box;
  padding: 8px;
}

/* 新增实现垂直居中的伪元素 */
.text-container::before {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width: 0;
}

完整HTML代码

<div class="diamond-container">
  <div class="diamond-left-textwrap"></div>
  <div class="diamond-right-textwrap"></div>
  <div class="diamond-shape"></div>
  <div class="text-container" contenteditable="true">
    Click To Edit
  </div>
</div>

核心改动说明

  1. 移除了左右绕排元素不必要的clip-path、position: relative和z-index属性,仅保留核心的shape-outside实现文本绕排逻辑,不影响原有效果。
  2. 新增.text-container::before伪元素实现文本的垂直居中,不管编辑时文本行数如何变化,都会始终保持在菱形的垂直居中位置。
  3. 给.text-container加了内边距和取消默认外框,避免文本贴边和编辑时出现多余的外边框。
  4. 完全保留了原有实现的父容器绝对定位、菱形外观(大小、边框、旋转角度),没有任何改动。

可选优化方案

如果想减少DOM节点数量,也可以直接给.text-container设置shape-inside: polygon(50% 0, 100% 50%, 50% 100%, 0 50%)属性,不需要两个额外的绕排DIV,不过shape-inside目前浏览器兼容性比shape-outside差,适合只需要兼容高版本浏览器的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:24:06