纯CSS实现未读消息显示99+

在大佬那看到这个小技巧,我觉得这个功能点还挺常用,所以给大家分享下具体的实现。当未读消息数小于100的时候显示准确数值,大于99的时候显示99+。

1. 实现效果
2. 组件封装
html 复制代码
<template>
  <span class="col">
    <sup :style="{'--num':num}">{{num}}</sup>
  </span>
</template>

<script>
export default {
  name: 'unread',
  props:{
    num:{
      type: Number,
      default: 0
    }
  }
}
</script>
<style>
.col {
  display: inline-flex;
  width: 4rem; height: 4rem;
  align-items: center;
  justify-content: center;
}

.col sup {
  position: absolute;
  box-sizing: border-box;
  min-width: 1rem;
  padding: 0 0.1875rem;
  color: #fff;
  font-size: min(.75rem, calc(10000px - var(--num) * 100px));
  line-height: 1.2;
  text-align: center;
  background-color: #eb4646;
  border: 1px solid #fff;
  border-radius: 1rem;
  transform: translate(calc(40% + .375rem), -.75rem);
  /* 数值为0的时候隐藏 */
  opacity: var(--num);
}
.col sup::before {
  content: '99+';
  font-size: min(.75rem, calc(var(--num) * 100px - 9900px));
}
</style>
3. 使用
html 复制代码
      <Unread :num="0"/> // 为0隐藏
      <Unread :num="9"/>
      <Unread :num="99"/>
      <Unread :num="999"/>
相关推荐
PedroQue9921 分钟前
Vite插件v0.2.6:架构优化与自动化升级
前端·vite
threerocks2 小时前
什么?我连 A2A、MCP 都没学会,现在又来了 AG-UI、A2UI.
前端·aigc·ai编程
牛奶2 小时前
如何自己写一个浏览器插件?
前端·chrome·浏览器
亿元程序员3 小时前
为什么Cocos都4.0了还有人用2.x?
前端
MomentYY3 小时前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
鹏毓网络科技3 小时前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
没烦恼3013 小时前
无痕模式下 HTTP\-First 拦截引发的“页面刷新”误判
前端
文心快码BaiduComate3 小时前
从个人提效到组织提效:Comate辅助构建自我进化的AI研发系统
前端·程序员
hunterandroid4 小时前
Compose 状态管理:remember、rememberSaveable 与状态提升
前端
星栈4 小时前
Dioxus 接数据库最容易写歪的 3 个地方:sqlx + SQLite 怎么接才顺
前端·rust·前端框架