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

React中如何给含自定义序号的有序列表项添加完整下划线?

问题:自定义有序列表实现全项下划线

我正在制作一个按获胜次数对用户排名的排行榜。由于为有序列表(ol)的第一名使用了自定义图片,无法使用Bootstrap内置的列表样式(list-group、list-group-item等)。请问如何实现让整个列表项(包含序号部分)显示下划线?

React代码

<React.Fragment>
  <div className="card">
    <div className="card-header">
      Leader Board
    </div>
    <ol start="1" className="firstItem ">
      {mainAccountsList.map(({userName}, i) => { 
        if (i === 0) {
          return (
            <React.Fragment>
            <li className='secondItem px-0'>{userName}</li>
            <span></span>
            </React.Fragment>)
        } else
        return (
          <React.Fragment>
            <li className='thirdItem'>{userName}</li>
            <span className='listBorder'></span>
          </React.Fragment>
      )})}
    </ol>
  </div>
</React.Fragment>

CSS代码

.firstItem  {
  background-image: url(crown-solid.svg);
  background-size: 20px;
  background-repeat: no-repeat;
  background-position: 3% 1%;
  margin-top: 5px;
  
} 

.secondItem  {
  list-style-type: none;
  margin-bottom: 5px;
} 

.thirdItem {
  margin-bottom: 5px;
}

.crown {
  fill: gold;
}

当前效果

当前效果

期望效果

期望效果


解决方案

要实现整个列表项(包含序号/自定义图标区域)的下划线,可通过调整结构和CSS样式来实现:

1. 简化React结构

去掉冗余的<span>和<React.Fragment>,让每个列表项统一由<li>承载:

<React.Fragment>
  <div className="card">
    <div className="card-header">
      Leader Board
    </div>
    <ol className="leaderboard-list">
      {mainAccountsList.map(({userName}, i) => (
        <li key={i} className={`leaderboard-item ${i === 0 ? 'first-place' : ''}`}>
          {userName}
        </li>
      ))}
    </ol>
  </div>
</React.Fragment>

2. 修改CSS样式

通过绝对定位放置图标/序号,给<li>设置贯穿整个宽度的底部边框:

.leaderboard-list {
  list-style: none;
  padding-left: 0;
  margin-top: 5px;
}

.leaderboard-item {
  padding: 8px 8px 8px 40px; /* 左侧预留图标/序号位置 */
  border-bottom: 1px solid #dee2e6; /* 下划线样式,可自定义颜色 */
  position: relative;
  margin-bottom: 0;
}

/* 第一名的皇冠图标 */
.leaderboard-item.first-place::before {
  content: '';
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  background-image: url(crown-solid.svg);
  background-size: contain;
  background-repeat: no-repeat;
}

/* 其他名次的自动序号 */
.leaderboard-item:not(.first-place)::before {
  content: counter(list-item);
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-weight: bold;
}

效果说明

  • 用counter(list-item)自动生成有序序号,摆脱<ol>默认样式限制,同时保留排序逻辑
  • 每个<li>设置统一左侧内边距,用来放置图标或序号,底部边框贯穿整个行宽
  • 通过绝对定位将图标/序号固定在左侧,确保内容对齐,下划线覆盖整个列表项区域

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:40:45