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

仿Google应用菜单:hover时文本换行方向异常问题求助

仿Google应用菜单文本换行问题解决

我正在开发仿Google的项目,当前制作应用菜单:

  • 服务名称过长时,默认仅显示第一行并添加省略号
  • hover服务项时,文本完整显示,第二行需在第一行下方展开(和Google官网一致)

当前HTML结构

<div class="google-apps-menu-container">
    <ul class="google-apps-menu">
        <li class="app-container">
            <div class="img-app-container"><img src="images/applogos/profile-photo.svg" alt="" id="user-profile-picture-for-apps" class="app-logo"></div>
            <p class="app-name">Cuenta</p>
        </li>
        <li class="app-container">
            <div class="img-app-container"><img src="images/applogos/search.svg" alt="" class="app-logo"></div>
            <p class="app-name">Búsquda</p>
        </li>
        <li class="app-container">
            <div class="img-app-container"><img src="images/applogos/bussisnes-logo.svg" alt="" class="app-logo"></div>
            <p class="app-name">Perfil de Empresa</p>
        </li>
    </ul>
</div>

当前CSS代码

.app-name
{
    position: absolute;
    bottom: 0;
    text-align: center;
    max-width: 11ch;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

遇到的问题

hover时将white-space设为normal后,文本虽能完整显示,但第二行出现在第一行上方,不符合预期(预期第二行在下方)。补充:.app-name为绝对定位,图片容器是flex布局的居中元素。

解决方案

问题根源是绝对定位的.app-name以底部为基准,换行后文本向上延伸。调整CSS如下:

/* 给父容器设置相对定位,确保子元素绝对定位的参考系正确 */
.app-container {
  position: relative;
  /* 设置容器高度,确保能容纳两行文本,根据实际需求调整 */
  height: 80px;
}

.app-name {
  position: absolute;
  bottom: 0;
  /* 用transform实现更稳定的水平居中,适配换行场景 */
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  max-width: 11ch;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.app-container:hover .app-name {
  white-space: normal;
  /* 微调底部位置,避免文本贴底 */
  bottom: 2px;
  /* 设置合适行高,让两行文本排版更美观 */
  line-height: 1.2;
}

说明

  1. 给.app-container添加position: relative,让.app-name的绝对定位基于父容器,而非全局
  2. 用transform: translateX(-50%)替代text-align: center,确保换行后的文本依然水平居中
  3. hover时调整bottom值和行高,让文本从底部向上展开,第二行自然出现在第一行下方
  4. 确保.app-container的高度足够容纳两行文本,避免内容被截断

内容的提问来源于stack exchange,提问作者Santiago Gómez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:01:06