如何使自定义<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>
实现原理
- 给
<li>设置position: relative,让伪元素before可以基于<li>定位 - 通过
padding-left为自定义编号预留左侧空间,避免内容被编号遮挡 - 将
li:before设置为position: absolute,固定在<li>的左侧位置 <li>内部的<div>作为块级元素,会自动保持垂直堆叠的布局,无需额外包裹容器
内容的提问来源于stack exchange,提问作者physicsboy
相关产品推荐
相关产品推荐

