

新闻资讯
技术学院本教程探讨如何使用css优雅地创建带有彩色圆形数字标记的有序列表,同时确保多行文本的正确缩进和``等语义化标签的正常显示。通过结合`::before`伪元素与`position: relative`及`position: absolute`属性,我们能够将自定义标记定位在列表项内容流之外,从而解决传统方法中遇到的缩进和布局冲突问题,实现既美观又语义化的列表样式。
在网页设计中,我们经常需要对有序列表(
在实现上述需求时,开发者通常会尝试几种方法,但每种方法都可能带来特定的挑战。
这种方法通过移除默认的列表标记(list-style: none),然后利用 ::before 伪元素和 CSS counter 来生成自定义的数字标记。我们可以轻松地为 ::before 伪元素设置背景色、边框半径等,使其呈现为彩色圆形数字。
/* 有序列表容器样式 */
.round-number-list-b {
margin-left: 0 !important;
padding-left: 0 !important;
counter-reset: item; /* 重置计数器 */
}
/* 列表项样式 */
.round-number-list-b > li {
margin-left: 0;
padding-left: 0;
counter-increment: item; /* 增加计数器 */
list-style: none inside; /* 移除默认标记 */
margin-bottom: 0.5rem;
}
/* 数字标记伪元素样式 */
.round-number-list-b > li:before {
display: inline-block; /* 使伪元素成为行内块级元素 */
width: 1.5rem;
aspect-ratio: 1/1; /* 保持宽高比为1:1,确保圆形 */
content: counter(item); /* 显示计数器值 */
padding: 0.1rem;
margin-right: 1.2rem;
font-weight: 900;
color: white;
background: #005577;
border-radius: 5rem; /* 大半径确保圆形 */
text-align: center;
}挑战: 这种方法的主要问题在于,当列表项内容是多行文本时,第二行及后续行不会自动缩进,而是从列表项的最左侧开始,导致文本与数字标记无法对齐,影响可读性。
为了解决多行文本缩进问题,一些开发者会尝试在列表项
.round-number-list > li {
display: flex; /* 启用Flex布局 */
align-items: flex-start; /* 确保内容从顶部对齐 */
}
.round-number-list > li:before {
flex: 0 0 1.3rem; /* 固定伪元素的宽度,不伸缩 */
/* 其他样式同方法一 */
}挑战: display: flex 虽然解决了缩进问题,但它改变了
标签
为了规避上述问题,一种直接但不够优雅的解决方案是在每个
标签,将所有内容放入
中。这样,
负责内容布局。
Click on the Inbox in the global navigation.
挑战: 这种方法虽然有效,但增加了 HTML 结构的冗余和复杂性。对于非专业编码人员来说,维护和使用这样的列表结构会变得更加困难,且不符合语义化的最佳实践。
最优雅且兼容性良好的解决方案是利用 CSS 的 position 属性,将 ::before 伪元素从列表项的正常文档流中分离出来,从而避免其对列表项内容布局的影响。
核心思想:
通过这种方式,::before 伪元素(即彩色数字圆圈)将独立于
/* 有序列表容器样式 */
ol.custom-numbered-list {
counter-reset: count; /* 重置计数器 */
list-style: none; /* 移除默认列表标记 */
padding: 10px 50px; /* 调整整体内边距,为数字标记预留空间 */
font-weight: 500;
}
/* 列表项样式 */
ol.custom-numbered-list li {
margin: 0 0 0.5rem 0; /* 列表项间距 */
counter-increment: count; /* 增加计数器 */
position: relative; /* 设置为定位上下文 */
padding-left: 35px; /* 为数字标记预留左侧空间,确保文本起始位置 */
}
/* 数字标记伪元素样式 */
ol.custom-numbered-list li::before {
content: counter(count); /* 显示计数器值 */
color: #fff;
font-size: .8rem;
font-weight: bold;
position: absolute; /* 绝对定位 */
--size: 23px; /* 定义数字圆圈的尺寸 */
/* 计算左侧定位:-1 * 圆圈宽度 - 圆圈与文本的间距 */
left: calc(-1 * var(--size) - 10px);
/* 也可以直接指定一个固定值,例如 left: -35px; */
line-height: var(--size); /* 行高与高度相等,实现数字垂直居中 */
width: var(--size);
height: var(--size);
background: #a1a; /* 背景色 */
border-radius: 50%; /* 圆形 */
text-align: center; /* 数字水平居中 */
}
- Peaches
- Apples
- Plums
- Click on the Inbox in the global navigation to access your messages and notifications.
- This is a very long list item that will wrap onto multiple lines. Notice how the second line is perfectly indented, aligning with the first line of text, not with the number circle.
size) + 10px 的绝对值,以避免文本与数字重叠。