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

如何为动态添加的<div>设置文本溢出可见且无滚动条?

解决动态添加元素的文本溢出可见问题

你的问题核心是固定尺寸的父元素(.tile)裁剪了超出尺寸的文本,同时Grid布局的默认行为也会限制子元素溢出单元格,即使overflow设为visible也会被裁剪。以下是具体解决方法:

问题根源

  1. .tile设置了固定的width和height,而字体尺寸是其2倍,文本超出父元素边界后被裁剪
  2. Grid布局的单元格默认会限制子元素的溢出范围,即使子元素设置overflow: visible也无法突破单元格限制

解决方案

方法1:用绝对定位让文本脱离父元素尺寸限制

保留.tile的固定宽高(维持背景方块大小),将文本元素设为绝对定位,使其脱离文档流,不受父元素尺寸约束:

.tile {
  display: block;
  width: var(--tileWidth);
  height: var(--tileWidth);
  position: relative; /* 为绝对定位子元素提供定位参考 */
  background-color: teal;
  font-size: calc(var(--tileWidth)*2);
  color: tomato;
  padding: 0;
  text-align: center;
  font-family: Impact;
  overflow: visible; /* 显式声明允许溢出,确保兼容 */
}

.letter {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 保持文本居中 */
  margin: 0;
  overflow: visible;
}

方法2:移除父元素固定尺寸,改用最小尺寸

如果不需要严格固定.tile的大小,将width和height改为min-width和min-height,让父元素自动适应文本尺寸:

.tile {
  display: block;
  min-width: var(--tileWidth);
  min-height: var(--tileWidth);
  position: relative;
  background-color: teal;
  font-size: calc(var(--tileWidth)*2);
  color: tomato;
  padding: 0;
  text-align: center;
  font-family: Impact;
}

修改后的完整代码

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" class="container"></div>

CSS

:root {
  --tileWidth: 30px;
}

.container {
  display: grid;
  grid-template-columns: repeat(16, var(--tileWidth)); /* 用repeat简化重复代码 */
}

.tile {
  display: block;
  width: var(--tileWidth);
  height: var(--tileWidth);
  position: relative;
  background-color: teal;
  font-size: calc(var(--tileWidth)*2);
  color: tomato;
  padding: 0;
  text-align: center;
  font-family: Impact;
  overflow: visible;
}

.letter {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
  overflow: visible;
}

JavaScript

let container = document.querySelector("#container");
let string = "HELLO WORLD!";

for (row = 0; row < 11; row++) {
  for (col = 0; col < 16; col++) {
    let tile = document.createElement("div");
    
    container.appendChild(tile);
    $(tile).addClass("tile");
    
    if (row == 5 && col > 1 && col < 14) {
      let p = document.createElement("p");
      
      tile.appendChild(p);
      $(p).addClass("letter");
      $(p).text(string[col - 2]);
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:31:58