如何将自定义有序列表的序号设置为可点击链接?
解决方案
要让自定义序号「001」可点击跳转,核心是把序号纳入链接的可点击范围,同时保留原有样式。修改后的代码如下:
CSS 代码
body { font-family: "Space Mono", monospace; background-color: #e5e5e5; margin: 0; } h1 { text-align: center; } .custom-list { counter-reset: custom-counter; list-style-type: none; display: flex; flex-direction: column; gap: 1rem; padding: 0; max-width: 50%; margin: 0 auto; } .custom-list li { counter-increment: custom-counter; display: flex; border-bottom: 3px solid; padding-bottom: 1rem; } .custom-list li a { display: flex; justify-content: space-between; width: 100%; text-decoration: none; color: inherit; /* 继承文本颜色,避免链接默认蓝色 */ } .custom-list li a:before { content: "00" counter(custom-counter); margin-right: 1rem; /* 调整序号与文本的间距 */ }
HTML 代码
<head> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap" rel="stylesheet" /> </head> <main> <h1>Test</h1> <hr /> <ol class="custom-list"> <li><a href="#">Test</a></li> <!-- 可添加更多列表项,序号会自动递增为002、003... --> </ol> </main>
修改说明
- 将计数递增操作从伪元素移到
<li>标签上,确保每个列表项的序号正确累加 - 让
<a>标签占满整个<li>的宽度,并设置为 flex 布局,继承原有内容的对齐方式 - 把「00X」序号改为
<a>标签的伪元素,这样点击序号就会触发链接跳转 - 给链接添加
color: inherit避免默认蓝色破坏原有样式,可根据需求调整
内容的提问来源于stack exchange,提问作者Hello
相关产品推荐
相关产品推荐

