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

如何创建响应式正方形div:宽高与单个字符高度完全相等

解决方案:创建与字符高度相等的响应式正方形div

你的问题核心在于对CSS中百分比内边距的理解偏差——所有padding和margin的百分比值,都是基于包含块的宽度计算的,不管是上下方向还是左右方向。所以你把padding-bottom:100%换成padding-right:100%时,它还是取父元素宽度的100%,自然无法匹配字符的高度。

下面给你两种可行的纯CSS方案,都能实现响应式需求:

方案一:使用aspect-ratio属性(现代浏览器推荐)

aspect-ratio是CSS新增的属性,可以直接定义元素的宽高比。我们让div的高度占满父元素(也就是字符的高度),然后设置宽高比为1:1,这样宽度就会自动等于高度:

<table border="1" style="position:relative;">
  <tr>
    <td style="font-size:144px; position:relative;">
      &nbsp;
      <div style="position:absolute; top:0; left:0; background-color:red; height:100%; aspect-ratio:1/1;"></div>
    </td>
  </tr>
</table>

当你修改font-size时,td的高度会跟着字符大小变化,div的height:100%会继承这个高度,aspect-ratio:1/1则让宽度自动匹配高度,完美实现响应式。

方案二:使用writing-mode兼容旧浏览器

如果需要兼容不支持aspect-ratio的旧浏览器,可以通过writing-mode改变布局方向,让百分比内边距基于高度计算:

<table border="1" style="position:relative;">
  <tr>
    <td style="font-size:144px; position:relative;">
      &nbsp;
      <div style="position:absolute; top:0; left:0; background-color:red; height:100%; writing-mode: vertical-lr; padding-bottom:100%;"></div>
    </td>
  </tr>
</table>

writing-mode: vertical-lr会把元素的布局方向改为垂直,此时padding-bottom的百分比将基于包含块的高度计算,设置为100%后,元素的宽度就会等于高度,达到你想要的效果。

另外,注意要给td加上position:relative,这样绝对定位的div才会以td为包含块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:40:17