要用CSS高效绘制带背景色的自定义数字样式,你可以使用伪元素和CSS计数器来实现。以下是一个示例代码,展示了如何创建一个带背景色的自定义数字样式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Number Style</title>
<style>
/* 重置列表样式 */
ol.custom-numbers {
list-style: none;
counter-reset: custom-counter;
padding-left: 0;
}
/* 列表项样式 */
ol.custom-numbers li {
counter-increment: custom-counter;
margin-bottom: 10px;
position: relative;
padding-left: 40px;
}
/* 自定义数字样式 */
ol.custom-numbers li::before {
content: counter(custom-counter);
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 30px;
height: 30px;
background-color: #007bff;
color: white;
border-radius: 50%;
text-align: center;
line-height: 30px;
font-size: 16px;
font-weight: bold;
}
</style>
</head>
<body>
<ol class="custom-numbers">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ol>
</body>
</html>
counter-reset: custom-counter;
:初始化一个名为 custom-counter
的计数器。counter-increment: custom-counter;
:在每个列表项中递增计数器。li::before
:使用伪元素 ::before
来显示计数器的值,并应用自定义样式。content: counter(custom-counter);
:将计数器的值插入到伪元素中。background-color: #007bff;
:设置背景颜色。border-radius: 50%;
:将背景形状设置为圆形。text-align: center;
和 line-height: 30px;
:确保数字在圆形背景中居中显示。这种方法适用于需要自定义数字样式的有序列表,并且可以轻松扩展到其他类似的场景。