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

如何实现Flex布局行内最后一个元素的文本省略

解决方案:Flex布局下实现最后一个元素文本省略并支持搜索高亮

问题分析

当前代码中,.contacts-section作为Flex容器,第二个.contact元素(承载联系人姓名)会默认根据内容自适应宽度,未被限制在容器剩余空间内,导致.location-text的text-overflow: ellipsis规则无法触发。

修复步骤

1. 调整Flex布局的宽度约束

修改CSS,给最后一个.contact元素添加flex: 1,让它强制占据容器剩余空间;同时给.location-text设置宽度占满父元素,确保文本在约束范围内:

.contacts-section {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-top: 4px;
  width: 100%;
  @include text(0.875rem);
}
.contact {
  display: flex;
  flex-direction: row;
  align-items: center;
  /* 让最后一个.contact占据容器剩余空间 */
  &:last-child {
    flex: 1;
  }
  .partner-text {
    margin-right: 16px;
    white-space: nowrap;
  }
  .location-text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    /* 确保文本容器占满父元素可用宽度 */
    width: 100%;
  }
}
.partner-icon,
.contact-icon {
  margin-right: 4px;
  width: 12px;
  height: 12px;
}

2. 兼容v-html搜索高亮场景

当使用v-html渲染带高亮标签的文本时,需确保高亮标签不会破坏不换行规则,给高亮类添加样式:

/* 自定义高亮样式,确保不换行 */
.highlight {
  white-space: nowrap;
  background-color: #ffeb3b;
}

3. Vue模板与逻辑示例(支持搜索高亮)

模板调整:

<div class="contacts-section">
  <div class="contact" v-if="contact.company">
    <forge-icon :image-name="'BriefcaseDark'" class="partner-icon" />
    <div class="partner-text" v-html="highlightMatch(contact.company)"></div>
  </div>
  <div class="contact">
    <forge-icon :image-name="'ProfileDarkSmall'" class="contact-icon" />
    <div class="location-text" v-html="highlightMatch(contact.name)"></div>
  </div>
</div>

对应Vue逻辑:

import { ref } from 'vue';

const searchKeyword = ref('');

// 匹配关键词并添加高亮标签
function highlightMatch(text) {
  if (!searchKeyword.value) return text;
  const matchRegex = new RegExp(`(${searchKeyword.value})`, 'gi');
  return text.replace(matchRegex, '<span class="highlight">$1</span>');
}

核心原理

  • flex: 1 强制最后一个.contact元素占据容器剩余空间,限制其最大宽度
  • .location-text设置width: 100%,让文本容器在父元素宽度约束内,此时overflow: hidden和text-overflow: ellipsis才能生效
  • 高亮标签添加white-space: nowrap,避免换行破坏整体省略效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:32:15