你真的会 flex 超长省略吗?

听说你很会处理超长省略?

话不多说,请做题。

1. 不定宽省略

需求

如下图,左右两大块内容保持 8px 的距离,左侧中间内容区域可能超长,需要做省略处理。
UI

实现

也许你会觉得这样的布局太简单:“直接 flex 一把梭”。

Dom结构

<div class="wrapper">
  <div class="left">
    <div class="start">Icon.</div>
    <div class="center">Content Detail: ABCDEFGHIJKLMNOPQRSTUVWXYZ</div>
    <div class="end">Else</div>
  </div>
  <!-- 右侧宽度不固定,但需要一行展示 -->
  <div class="right">More Detail</div>
</div>

CSS设计

.wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 520px;
  background: #eee;
  padding: 4px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.right {
  /* 确保right部分展示完全,不被压缩 */
  flex-shrink: 0;
  margin-left: 8px;
}

.left {
  display: flex;
}

.start {
  background: #ddd;
}

.center {
  margin: 0 8px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.end {
  background: #ddd;
}

效果

怎么溢出了? 🤷‍♂️🤷‍♀️
在这里插入图片描述

反思

于是你开始反思:

  • “咦,好像哪里不对?没给.center设置宽度,肯定不能出现省略号呀!”
  • “那我怎么知道宽度是多少?右侧内容不定宽啊!”

于是,你随便做了一个尝试,

.left {
  display: flex;
+ width: 100%;
}

可惜结果还是不行(100%那是真的傻)。


你再想:

  • “既然右侧宽度是需要不被挤压固定的,那是用了 flex 之后左侧的宽度其实已经确定了!“
  • ”既然左侧宽度是相对已知的,那么如果 .left 超长了,设置 overflow 后它的子元素就一定会省略!!!“

于是,你迈出了成功的一步。

.left {
  display: flex;
+ overflow: hidden;
}

恭喜你

其实只要理解了在 flex 布局中相对宽度的概念,问题就迎刃而解了。
在这里插入图片描述

其实这题还有个解:

.left {
  display: flex;
+ flex-grow: 1;
+ /* 可以偷懒用flex: 1 */
+ /*  flex: 1; */
+ width: 0;
}

设置 .left 元素的宽度为 0 后,该元素不再有原始内容宽度,再借助 flex: 1 可以分配到父元素的剩余宽度,从而实现预期效果。

2. 定宽不定项

需求

如下图,整个组件总最宽限制 520px。

最多有 4 个 tab,每个 tab 限制宽度最长为 120px,如相对总长度有富余宽度,则留给最后一项。
在这里插入图片描述

分析

如果理解上一题中提到的“相对宽度”的概念,这题也就手到擒来了。

对于整个 520px 宽度的组件来说,最后一项 tab 的宽度就是除去其他几个 tab 的宽度后剩余的部分。

即,这题中的最后一项,就是上一题中的.left

实现

还是 flex 。

Dom结构

<div class="wrapper2">
  <div class="item">
    <div class="name">Tab 1</div>
    <div class="sep">/</div>
  </div>
  <div class="item">
    <div class="name">This is Tab 2, This is Tab 2</div>
    <div class="sep">/</div>
  </div>
  <div class="item">
    <div class="name">Tab 3</div>
    <div class="sep">/</div>
  </div>
  <div class="item">
    <div class="name">This is Tab 4,This is Tab 4,This is Tab 4</div>
  </div>
</div>

CSS设计

.wrapper2 {
  margin-top: 16px;
  display: flex;
  align-items: center;
  max-width: 520px;
  background: #eee;
  padding: 4px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.item {
  display: flex;
}

.name {
  max-width: 120px;
  background: #ddd;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.item:last-of-type {
  overflow: hidden;
  /* flex-grow: 1;
    width: 0; */
}

.item:last-of-type .name {
  max-width: initial;
}

.sep {
  margin: 0 8px;
}

结果

在这里插入图片描述

彩蛋🎉

完整的实现

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值