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

如何使自定义<ol>编号与<li>内内容垂直对齐且无需额外容器?

解决方案

可以通过绝对定位+内边距的方式实现,无需添加额外容器,具体修改如下:

修改后的CSS代码

* {
  font-family: arial;
}

ol {
  list-style: none;
  counter-reset: test;
  padding-left: 0; /* 清除默认列表内边距 */
}

li {
  counter-increment: test;
  position: relative;
  padding-left: 36px; /* 为自定义编号预留空间 */
  margin-bottom: 16px; /* 可选:列表项之间的间距 */
}

li:before {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  content: counter(test);
  background: black;
  color: white;
  position: absolute;
  left: 0;
  top: 0; /* 若要编号与内容垂直居中,可替换为:top: 50%; transform: translateY(-50%); */
}

.head {
  font-weight: bold;
}

对应的HTML代码

<ol>
  <li>
      <div class="head">Item 1</div>
      <div class="sub-head">Some text</div>
  </li>
  <li>
      <div class="head">Item 2</div>
      <div class="sub-head">Another text line here</div>
  </li>
</ol>

实现原理

  1. 给<li>设置position: relative,让伪元素before可以基于<li>定位
  2. 通过padding-left为自定义编号预留左侧空间,避免内容被编号遮挡
  3. 将li:before设置为position: absolute,固定在<li>的左侧位置
  4. <li>内部的<div>作为块级元素,会自动保持垂直堆叠的布局,无需额外包裹容器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:01:11