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

为何grid布局中的div无法使text-overflow属性生效?

修复响应式文本截断问题

问题原因

连续无空格的长文本会撑破父容器,且你的.account-section元素未设置明确宽度限制,导致.container溢出main,最终text-overflow: ellipsis无法生效。

修复步骤

  1. 给.account-section添加width: 100%和box-sizing: border-box,让它严格继承父容器宽度,且内边距计入宽度,避免被长文本撑开。
  2. 给.username补充max-width: 100%,确保文本不会超出父元素范围,配合原有三个属性实现单行省略。

修改后的完整代码

<main>
    <div class="container">
        <section class="account-section">
            <h5 class="username">WWWWWWWWWWWWWWWWW</h5>
        </section>
    </div>
</main>

<style>
main {
    height: 200px;
    display: grid;
    place-items: center;
    padding: 50px;
    box-sizing: border-box; /* 可选:避免padding导致main自身溢出视口 */
}

.container {
    position: relative;
    display: grid;
    max-width: 1240px;
    width: 100%;
}

.account-section {
    height: fit-content;
    background: var(--white);
    box-shadow: 0 0 50px rgb(0, 0, 0, 0.15);
    padding: 25px;
    position: relative;
    width: 100%; /* 关键:限制宽度 */
    box-sizing: border-box; /* 关键:内边距计入宽度 */
}

.username {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    max-width: 100%; /* 确保文本不超出父元素 */
}
</style>

补充说明

  • box-sizing: border-box是核心,它让元素宽度包含内边距和边框,避免布局溢出。
  • 单行文本省略必须同时满足text-overflow: ellipsis、white-space: nowrap、overflow: hidden三个属性,且元素要有明确的宽度限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:01:03